Skip to content

Instantly share code, notes, and snippets.

@jbottigliero
Created December 16, 2013 04:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jbottigliero/7982340 to your computer and use it in GitHub Desktop.
Save jbottigliero/7982340 to your computer and use it in GitHub Desktop.
React <select> Component (JSX)
/** @jsx React.DOM */
define(['reactjs'], function(React){
return React.createClass({
getDefaultProps: function(){
return {
multiple: false
/*
name: 'mySelect'
options: [
{
value: optionOne
label: "Option One"
},
{
value: optionsTwo
label: "Option Two",
selected: true,
}
]
*/
}
},
render: function() {
// the default value for the <select> (selected for ReactJS)
// http://facebook.github.io/react/docs/forms.html#why-select-value
var defaultValue;
var options = this.props.options.map(function(opt, i){
// if this is the selected option, set the <select>'s defaultValue
if (opt.selected === true || opt.selected === 'selected') {
// if the <select> is a multiple, push the values
// to an array
if (this.props.multiple) {
if (defaultValue === undefined) {
defaultValue = [];
}
defaultValue.push( opt.value );
} else {
// otherwise, just set the value.
// NOTE: this means if you pass in a list of options with
// multiple 'selected', WITHOUT specifiying 'multiple',
// properties the last option in the list will be the ONLY item selected.
defaultValue = opt.value;
}
}
// attribute schema matches <option> spec; http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.6
// EXCEPT for 'key' attribute which is requested by ReactJS
return <option key={i} value={opt.value} label={opt.label}>{opt.label}</option>;
}, this);
return <select
defaultValue={defaultValue}
multiple={this.props.multiple}
name={this.props.name}
>
{options}
</select>;
}
});
});
@relaxnow
Copy link

Thanks for the hint to put defaultValue on the !

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