Skip to content

Instantly share code, notes, and snippets.

@zackperdue
Last active January 17, 2020 19:25
Show Gist options
  • Save zackperdue/970e4a8c9bf981625013 to your computer and use it in GitHub Desktop.
Save zackperdue/970e4a8c9bf981625013 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;
@thomasam97
Copy link

hey how are you handeling licensing?
greetings thomas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment