Reputation: 4438
I have a long enough text that is copied from another site, I have to make sure that when the user clicks on the button, the text is taken and copied into the value
variable.
I tried using getData
, but it doesn't work.
Can you give me a hand?
Link: codesandbox
Code:
import React, { useState, useEffect, useRef } from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
export default function MultilineTextFields() {
const [value, setValue] = React.useState("");
const ref = useRef(null);
return (
<Box
component="form"
sx={{
"& .MuiTextField-root": { m: 1, width: "25ch" }
}}
noValidate
autoComplete="off"
>
<Button
variant="contained"
color="primary"
onClick={(e) => {
let paste = (e.clipboardData || window.clipboardData).getData("Text");
setValue(paste);
}}
>
Paste
</Button>
<div>
<TextField
ref={ref}
id="outlined-multiline-static"
label="Multiline"
multiline
rows={40}
value={value}
/>
</div>
</Box>
);
}
Upvotes: 3
Views: 9780
Reputation: 409
It should be noted that this method is not entirely cross-platform. See Here for the compatibility.
You can use the clipboard API, It can be used like this:
navigator.clipboard.readText()
.then(text => {
console.log('Pasted content: ', text);
})
.catch(err => {
console.error('Failed to read clipboard contents: ', err);
});
Or with async syntax:
const text = await navigator.clipboard.readText();
Keep in mind that this will prompt the user with a permission request dialog box, so no funny business is possible.
The above code will not work if called from the console. It only works when you run the code in an active tab. To run the code from your console you can set a timeout and click in the website window quickly:
setTimeout(async () => {
const text = await navigator.clipboard.readText();
console.log(text);
}, 2000);
Read more on the API and usage in the Google developer docs.
You also probably can’t use this on code sandbox because it is a sandboxed environment.
Upvotes: 7