I am wondering if this is a good practise or not.
React doesn't offer solutions for all DOM events, so sometime's you need to reach out to the DOM and attach an event listener yourself. Just make sure you add it in componentDidMount and remove it in componentWillUnmount (see "Component Specs and Lifecycle
" )... Forgetting the latter will create a memory leak and attach a new listener every time the component is mounted.
var Box = React.createClass({
getInitialState: function() {
return {windowWidth: window.innerWidth};
},
handleResize: function(e) {
this.setState({windowWidth: window.innerWidth});
},
componentDidMount: function() {
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount: function() {
window.removeEventListener('resize', this.handleResize);
},
render: function() {
return <div>Current window width: {this.state.windowWidth}</div>;
}
});
Where you can solve the problem with React's events, you should. It'll save you time and offer a slight performance enhancement (not having to attach and remove handlers).
Samuel Oloruntoba
Java is to JavaScript what Car is to Carpet.
You could, but you will have to wait for the component to mount first before attaching the event. But, just because you can don't mean you should.
React handles events by delegating the events only when it's needed. Attaching events the
addEventListenerway can easily slow down the DOM especially if it's done a lot of time. But that aside you can, but do it sparingly.