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).