How to Get Pasted Value from Reactjs Onpaste Event

How to capture paste event anywhere on page in React?

  1. Your listener will only work when the specific div is focused, therefore it works on the second attempt. Instead, add the listener to body element or window object:
function Component() {
const [inputText, setInputText] = useState(false);

useEffect(() => {
window.addEventListener("paste", (e) => {
setInputText(e.clipboardData.getData("text"));
});

return () => {
window.removeEventListener("paste");
};
}, []);

return <div className="App">{inputText}</div>;
}

Edit Paste Listener



  1. am I right in thinking it's best to pass a callback

No, it depends on the depth, please read about Context API and research on an anti-pattern called "props-drilling".

Getting doubled value with an onPaste event on an input using React

You need to call event.preventDefault() after handling your paste event. As it is, the paste event is changing the state in handlePaste and then going on to add the pasted text to the input, triggering handleChange.

React TypeScript Input Paste Event

I know it has been a while since you asked, but I ran into the same problem today. Fixed it with:

event: React.ClipboardEvent

I'm trying detect if content pasted in input or was introduced from keyboard in ReactJS

May not answer perfectly your actual question, but note that the InputEvent interface has a .inputType property which will give you exactly this information, so if you don't target older browsers, you can only listen for the input event and check this property against "insertFromPaste" constant:

const onInput = (e) => {
const isPasted = e.nativeEvent.inputType.startsWith("insertFromPaste");
// ...
}

const target = document.getElementById('target');target.oninput = (evt) => {  const isPasted = evt.inputType && evt.inputType.startsWith("insertFromPaste");  target.classList.toggle('is-pasted', isPasted);};
.is-pasted { background-color: green; }
<div contenteditable id="target">edit me</div>

Using onPaste with react-select

I was fiddling a lot with that. I find it rather surprising that this is not one of the main features of react-select. Anyway, I've found a workaround for this:

<div style={{height: '100%', width: '100%' }} onPaste={(e) => console.log(e)}>
<Select .../>
</div>

This seems to do the trick and triggers the right event at the right time.



Related Topics



Leave a reply



Submit