From 153092896f1ae87b94fbffd451705f995c5465cf Mon Sep 17 00:00:00 2001 From: Connor McSheffrey Date: Sun, 6 Oct 2013 00:06:57 -0700 Subject: [PATCH] Add event listeners cookbook entry --- cookbook/cb-11-event-listeners.md | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 cookbook/cb-11-event-listeners.md diff --git a/cookbook/cb-11-event-listeners.md b/cookbook/cb-11-event-listeners.md new file mode 100644 index 00000000..7b206a86 --- /dev/null +++ b/cookbook/cb-11-event-listeners.md @@ -0,0 +1,37 @@ +--- +id: event-listeners +title: event listening in a React component +layout: docs +permalink: event-listeners.html +--- + +### Problem +You want to listen to an event inside a React component. + +### Solution +You can listen in componentDidMount. The below example will display the window dimensions. + +```js +var WindowDimensions = React.createClass({ + render: function() { + return {this.state.width} x {this.state.height}; + }, + updateDimensions: function() { + this.setState({width: $(window).width(), height: $(window).height()}); + }, + componentWillMount: function() { + this.updateDimensions(); + }, + componentDidMount: function() { + window.addEventListener("resize", this.updateDimensions); + // Using jQuery $(window).on('resize', this.updateDimensions); + }, + componentWillUnmount: function() { + window.removeEventListener("resize", this.updateDimensions); + // Using jQuery $(window).off('resize', this.updateDimensions); + } +}); +``` + +### Discussion +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