You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.1 KiB
41 lines
1.1 KiB
11 years ago
|
---
|
||
|
id: dom-event-listeners
|
||
|
title: DOM event listeners in a component
|
||
11 years ago
|
layout: cookbook
|
||
11 years ago
|
permalink: dom-event-listeners.html
|
||
11 years ago
|
prev: props-in-getInitialSate-as-anti-pattern.html
|
||
|
next: initial-ajax.html
|
||
11 years ago
|
---
|
||
|
|
||
|
> Note:
|
||
|
>
|
||
11 years ago
|
> This entry shows how to attach DOM events not provided by React ([check here for more info](/react/docs/cookbook/events.html)). This is good for integrations with other libraries such as jQuery.
|
||
11 years ago
|
|
||
11 years ago
|
Try to resize the window:
|
||
11 years ago
|
|
||
|
```js
|
||
|
/** @jsx React.DOM */
|
||
|
|
||
|
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>;
|
||
|
}
|
||
|
});
|
||
|
|
||
|
React.renderComponent(<Box />, mountNode);
|
||
|
```
|
||
|
|
||
|
`componentDidMount` is called after the component's mounted and has a DOM representation. This is often a place where you'd attach generic DOM events.
|