Skip to content

Instantly share code, notes, and snippets.

@puiutucutu
Forked from zackperdue/DropdownMenu.jsx
Created March 2, 2017 15:51
Show Gist options
  • Save puiutucutu/e8265688c3154b689e30e5f5ceff39ac to your computer and use it in GitHub Desktop.
Save puiutucutu/e8265688c3154b689e30e5f5ceff39ac to your computer and use it in GitHub Desktop.
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment