Skip to content

Instantly share code, notes, and snippets.

@zackperdue
Last active January 17, 2020 19:25
Show Gist options
  • Select an option

  • Save zackperdue/970e4a8c9bf981625013 to your computer and use it in GitHub Desktop.

Select an option

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;
@zackperdue

Copy link
Copy Markdown
Author

How to use

<DropdownMenu options={[Array]} groupBy={[String]} placeholder={[String]} selected={[ID]} />

I created this to show categories in a dropdown menu grouped by optgroups. Below is the structure that this element accepts for options:

  • categories
    • id
    • name
    • subcategories
      • id
      • name

groupBy

This prop is used to create optgroups. Set this to a string that can be called on the object.

@jgatjens

jgatjens commented Dec 3, 2015

Copy link
Copy Markdown

👍

@thomasam97

Copy link
Copy Markdown

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