Add event listeners cookbook entry
Connor McSheffrey committed
Oct 6, 2013 at 00:06 UTC
e0df9cbb01aa27953bf074703c6a5de5fc406891
1 file changed
+37
docs/cookbook/cb-11-event-listeners.md
new
+37
@@ -0,0 +1,37 @@
1
+---
2
+id: event-listeners
3
+title: event listening in a React component
4
+layout: docs
5
+permalink: event-listeners.html
6
+---
7
+
8
+### Problem
9
+You want to listen to an event inside a React component.
10
+
11
+### Solution
12
+You can listen in componentDidMount. The below example will display the window dimensions.
13
+
14
+```js
15
+var WindowDimensions = React.createClass({
16
+ render: function() {
17
+ return <span>{this.state.width} x {this.state.height}</span>;
18
+ },
19
+ updateDimensions: function() {
20
+ this.setState({width: $(window).width(), height: $(window).height()});
21
+ },
22
+ componentWillMount: function() {
23
+ this.updateDimensions();
24
+ },
25
+ componentDidMount: function() {
26
+ window.addEventListener("resize", this.updateDimensions);
27
+ // Using jQuery $(window).on('resize', this.updateDimensions);
28
+ },
29
+ componentWillUnmount: function() {
30
+ window.removeEventListener("resize", this.updateDimensions);
31
+ // Using jQuery $(window).off('resize', this.updateDimensions);
32
+ }
33
+});
34
+```
35
+
36
+### Discussion
37
+componentDidMount is invoked when the component has been mounted and has a DOM representation. Use this as an opportunity to operate on the DOM when the component has been initialized and rendered for the first time.
\ No newline at end of file