DOM Event Listeners in a Component

Note:

This entry shows how to attach DOM events not provided by React (check here for more info). This is good for integrations with other libraries such as jQuery.

Try to resize the window:

  1. var Box = React.createClass({
  2. getInitialState: function() {
  3. return {windowWidth: window.innerWidth};
  4. },
  5. handleResize: function(e) {
  6. this.setState({windowWidth: window.innerWidth});
  7. },
  8. componentDidMount: function() {
  9. window.addEventListener('resize', this.handleResize);
  10. },
  11. componentWillUnmount: function() {
  12. window.removeEventListener('resize', this.handleResize);
  13. },
  14. render: function() {
  15. return <div>Current window width: {this.state.windowWidth}</div>;
  16. }
  17. });
  18. ReactDOM.render(<Box />, mountNode);

componentDidMount is called after the component is mounted and has a DOM representation. This is often a place where you would attach generic DOM events.

Notice that the event callback is bound to the react component and not the original element. React automatically binds methods to the current component instance for you through a process of autobinding.