React doesn't work for preventDefault() on onCopy event
Sviat Kuzhelev
I'm trying to figure out how to make the clipboard event return false
on the onCopy event . I use test onCopy
handlers and e.preventDefault()
methods. But the text is copied to the buffer without a hitch! What am I missing?
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'));
Max Wolfen
This is a great question!
This happens because React's actual event listeners are also at the root of the document, which means the click event has bubbled up to the root. You can e.nativeEvent.stopImmediatePropagation()
use to block 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'));