How to copy text to the clipboard in React.js ?
The following example covers how to copy text to the clipboard in React JS using useState() hook.
- Basic knowledge of npm & create-react-app command.
- Basic knowledge of styled-components.
- Basic Knowledge of useState() React hooks.
Basic Setup: You will start a new project using create-react-app using the following command:
npx create-react-app react-copy-text
Now go to your react-copy-text folder by typing the given command in the terminal.
Required module: Install the dependencies required in this project by typing the given command in the terminal.
npm install --save styled-components npm install --save react-copy-to-clipboard
Now create the components folder in src then go to the components folder and create two files Clipboard.js and Styles.js.
Project Structure: The file structure in the project will look like this.
Example: We create a state with the first element copyText as an initial state having a value of the empty string and the second element as function setCopyText() for updating the state. Then a function is created by the name handleCopyText which sets the state value to the text we enter the input field. Another function copyToClipboard is created to copy the updated state value to the clipboard.
When we enter a text in our input field, handleCopyText function gets triggered through onChange event which sets the state to that entered value. Now when we click on the button ‘Copy to Clipboard’, the function copyToClipboard gets triggered through onClick event which copies the state value to the clipboard with copy() function. Now we can copy our text anywhere by just clicking Ctrl+V key.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: