user1481096
user1481096

Reputation: 317

Handle react event and legacy library event together

For example, when i wrote a dropdown class, my thought is like this

EVENT.listener(document, 'click', function(e) {
     // hide all active dropdowns
});

var DropDown = React.createClass({
    onClick: function(e) {
        // toggle self
        e.stopProbagation();
    }
});

However, the event in react and outside are different; so, the above code won't work. So, how to handle this? or is there another pattern to write the dropdown?

Upvotes: 2

Views: 507

Answers (1)

Ross Allen
Ross Allen

Reputation: 44900

componentDidMount is the best place to integrate other frameworks or native calls since React guarantees a component's real DOM node exists when componentDidMount is called.

To get similar functionality to your example, you could implement the function in your root React component and listen to the native DOM event there. When the click occurs, call into any components using their ref attributes that need to react to the click:

var RootComponent = React.createClass({
  componentDidMount: function() {
    document.addEventListener("click", this.hideOverlays, false);
  },

  componentWillUnmount: function() {
    document.removeEventListener("click", this.hideOverlays, false);
  },

  hideOverlays: function() {
    this.refs.dropdown.hide();
  },

  render: function() {
    return DropDown({ref: "dropdown"});
  }
});

var DropDown = React.createClass({
  getInitialState: function() {
    return {
      isVisible: false
    };
  },

  hide: function() {
    this.setState({isVisible: false});
  }

  render: function() {
    var style;
    if (!this.state.isVisible) style = {display: "none"};

    return React.DOM.div({style: style});
  };
});

Upvotes: 1

Related Questions