Created
December 16, 2013 04:29
-
-
Save jbottigliero/7982340 to your computer and use it in GitHub Desktop.
React <select> Component (JSX)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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>; | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the hint to put defaultValue on the !