React: Button Dropdown

This entry is part 34 of 35 in the series React JS

See the Pen React Dropdown by Tristan W (@tristaaan) on CodePen.

var Dropdown = React.createClass({
  getInitialState() {
    return { toggled: false };
  },
  componentDidUpdate: function(prevState) {
    if (this.state.toggled && !prevState.toggled) {
      window.addEventListener("click", this.handleClickOutside);
    } else if (!this.state.toggled && prevState.toggled) {
      window.removeEventListener("click", this.handleClickOutside);
    }
  },
  handleClickOutside: function(e) {
    var children = this.getDOMNode().getElementsByTagName("*");
    for (var x in children) {
      if (children[x] == e.target) {
        return;
      }
    }
    this.toggle();
  },
  toggle(e) {
    this.setState({ toggled: !this.state.toggled });
  },
  render() {
    var isHidden = !this.state.toggled ? "hidden" : "";
    return (
      <div className="dropdown">
        <button
          ref="dropdownButton"
          className="dropdown-button"
          onClick={this.toggle}
        >
          {this.props.buttonText}
        </button>
        <section
          ref="dropdownContent"
          className={isHidden + " dropdown-content"}
        >
          {this.props.children}
        </section>
      </div>
    );
  }
});

var Main = React.createClass({
  render() {
    return (
      <Dropdown buttonText="hello">
        <p>Goodbye</p>
      </Dropdown>
    );
  }
});

React.render(<Main />, document.getElementById("content"));
Series Navigation<< ReactJS: Change Color Simple Component
ReactJS: Hover over button >>