If you encounter any issues while adding the Clipboardjs
package in Laravel 10, follow these steps:
Package Installation-
Install the clipboardjs
via npm -
npm install clipboard --save
Verify if the package is included in package.json
-
cat package.json
The dependency should be listed there.
{
"dependencies": {
"clipboard": "^2.0.11"
}
}
Once confirmed that the package is installed and accessible in your Laravel app, proceed to initialize it.
Import Clipboard in resources/js/app.js
-
In resources/js/app.js
, import the ClipboardJS
class from the clipboard
package.
import ClipboardJS from 'clipboard';
Instantiate ClipboardJS class in resources/js/app.js
-
In resources/js/app.js
, create an instance of the ClipboardJS class from the clipboard
package.
new ClipboardJS('#copyToKeyboard');
Here, copyToKeyboard
refers to the id of the copy button to be clicked.
Using Clipboard in Blade file-
Add copy button and target element in your Laravel blade -
<input type="text" readonly id="slug" name="slug">
<span id="copyToKeyboard" data-clipboard-target="#slug">Copy</span>
[!NOTE]
The id="copyToKeyboard"
corresponds to the element for which we instantiated the ClipboardJS class.
[!NOTE]
The
data-clipboard-target="#slug"
represents the id of the target element whose value will be copied.
[!IMPORTANT]
Don't forget to include
@vite(['resources/css/app.css', 'resources/js/app.js'])
in your app.blade.php or parent blade layout to automatically build the js and css using the vite server.