Hello Developers, in this blog we are going to learn how we can add a copy text button to copy text in clipboard
First, create a new project using the below command:
npx create-react-app copy-text-app
Into your app js file make two functions:
First function to copy the text in clipboard and second function to get a copied text back from the clipboard
import { TextareaAutosize, Button } from '@mui/material' import { Box } from '@mui/system' import React, { useState } from 'react' const App = () => { const [textValue, setTextValue] = useState('') const copyHandler = (e) => { setTextValue(e.target.value) } const copyText = () => { navigator.clipboard.writeText(textValue) } const pasteText = () => { navigator.clipboard.readText().then(e => console.log(e)) } return ( <> <Box> <TextareaAutosize minRows={5} style={{ padding: '15px', fontSize: '20px' }} placeholder={'Enter a text'} cols={50} value={textValue} onChange={copyHandler} /> <Box display='flex' justifyContent='center' gap='15px'> <Button onClick={copyText}>Copy</Button> <Button onClick={pasteText}>Paste</Button> </Box> </Box> </> ) } export default App
Demo:
I hope this article is helpful for you 🙂