puiu91
3/2/2017 - 3:51 PM

ReactJS Dropdown Menu with optgroup

ReactJS Dropdown Menu with optgroup

import React from 'react';

var SelectInput = React.createClass({

  propTypes: {
    groupBy: React.PropTypes.string,
    options: React.PropTypes.array.isRequired,
    placeholder: React.PropTypes.string,
    selected: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      options: [],
      groupBy: null,
      selected: null
    };
  },

  getOptionTag: function(option) {
    return (
      <option value={option.id} key={option.id}>{option.name}</option>
    );
  },

  getOptionTags: function(options) {
    return options.map((option) => {
      return this.getOptionTag(option);
    });
  },

  getOptions: function() {
    var options = this.props.options;
    if (this.props.groupBy) {
      return this.getOptgroupTags(options);
    } else {
      return this.getOptionTags(options);
    }
  },

  getOptgroupTags: function(groups) {
    var optgroups = groups.map((group) => {
      var children = this.getOptionTags(group[this.props.groupBy]);
      return (
        <optgroup key={group.id} label={group.name}>
          {children}
        </optgroup>
      );
    });

    return optgroups;
  },

  render: function() {
    var options = this.getOptions();

    return (
      <select defaultValue={this.props.selected} {...this.props}>
        <option>{this.props.placeholder}</option>
        {options}
      </select>
    );
  }
});

export default SelectInput;