I'm trying to figure out how to make the clipboard events return false
on the onCopy event. I use for test the onCopy
handler and e.preventDefault()
method. But text is copied without obstacles to the buffer! What is I miss?
Thank You in Advance.
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import ReactDOMServer from 'react-dom/server';
import './index.css';
class Copy extends React.Component {
constructor(props) {
super(props);
this.state = {
time: '',
timer: false,
counter: 0
};
this.handlerCopy = this.handlerCopy.bind(this);
}
handlerCopy(e) {
e.preventDefault(); // must prevent the current event
this.setState(prevState => ({
counter: prevState.counter + 1
}));
alert('Don\'t copy it!');
}
render() {
return (
<React.Fragment>
<p onCopy={this.handlerCopy}>Copy me!</p>
<p>Copy count: {this.state.counter}</p>
</React.Fragment>
);
}
}
ReactDOM.render(
<Copy />,
document.getElementById('root'));
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.
You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement. click method.
It's a really good question!
This happens because React’s actual event listener is also at the root of the document, meaning the click event has already bubbled to the root. You can use e.nativeEvent.stopImmediatePropagation()
to prevent other event listeners.
Try it:
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import ReactDOMServer from 'react-dom/server';
import './index.css';
class Copy extends React.Component {
constructor(props) {
super(props);
this.state = {
time: '',
timer: false,
counter: 0
};
this.handlerCopy = this.handlerCopy.bind(this);
}
handlerCopy(e) {
console.log(e.target.innerHTML);
e.preventDefault();
e.nativeEvent.stopImmediatePropagation();
this.setState(prevState => ({
counter: prevState.counter + 1
}));
alert('Don\'t copy it!');
}
render() {
return (
<React.Fragment>
<p onCopy={this.handlerCopy}>Copy me!</p>
<p>Copy count: {this.state.counter}</p>
</React.Fragment>
);
}
}
ReactDOM.render(
<Copy />,
document.getElementById('root'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With