ReactJS: Dropdown with no windows listener

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

See the Pen React Dropdown – No Window Listener by daryl (@darylw) on CodePen.0

class Dropdown extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      expanded: false,
      value: "Donuts"
    };
  }

  expand() {
    this.setState({ expanded: true });
  }

  collapse() {
    this.setState({ expanded: false });
  }

  handleItemClick(e) {
    this.setState({
      expanded: false,
      value: e.target.innerText
    });
  }

  handleTriggerClick() {
    this.setState({ expanded: !this.state.expanded });
  }

  render() {
    let dropdown = undefined;
    if (this.state.expanded) {
      dropdown = (
        <div className="content">
          {this.props.options.map(item => {
            return (
              <div
                onClick={e => {
                  this.handleItemClick(e);
                }}
                className="item"
              >
                {item}
              </div>
            );
          })}
        </div>
      );
    }

    return (
      <div
        className={'dropdown ${this.state.expanded ? "active" : ""}'}
        tabIndex="0"
        onBlur={() => {
          this.collapse();
        }}
      >
        <div
          className="trigger"
          onClick={() => {
            this.handleTriggerClick();
          }}
        >
          {this.state.value}
        </div>
        {dropdown}
      </div>
    );
  }
}

ReactDOM.render(
  <Dropdown
    options={["Strawberry Cream", "Chocolate Flakes", "Marshmallow Sprinkles"]}
  />,
  document.getElementById("app")
);
Series Navigation<< ReactJS: Dropdown
ReactJS: How to define a required textfield >>

Leave a comment

Leave a Reply