Reputation: 9595
I am using React-Select.
Currently I am fetching data from elasticsearch and setting it to state:
var new_titles = []
body.hits.hits.forEach(function(obj){ // looping through elasticsearch
new_titles.push({value: obj._source.title_id, label: obj._source.title_name})
})
this.setState({titleResults: new_titles})
Later I am using this.state.titleResults
and passing it into my React-Select component:
<Select autofocus optionComponent={DropdownOptions} options={this.state.titleResults} simpleValue clearable={this.state.clearable} name="selected-state" value={this.state.selectedTitleValue} onChange={this.handleTitleChosen} searchable={this.state.searchable} />
This works fine. But now I would like to pass in extra meta data pertaining to this title when users search my React-Select componentOptions. Something like this:
I am only passing in {value: obj._source.title_id, label: obj._source.title_name}
, but I would like to pass in more information to be used by my DropdownOption
component:
const DropdownOptions = React.createClass({
propTypes: {
children: React.PropTypes.node,
className: React.PropTypes.string,
isDisabled: React.PropTypes.bool,
isFocused: React.PropTypes.bool,
isSelected: React.PropTypes.bool,
onFocus: React.PropTypes.func,
onSelect: React.PropTypes.func,
option: React.PropTypes.object.isRequired,
},
handleMouseDown (event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
},
handleMouseEnter (event) {
this.props.onFocus(this.props.option, event);
},
handleMouseMove (event) {
if (this.props.isFocused) return;
this.props.onFocus(this.props.option, event);
},
render () {
return (
<div className={this.props.className}
onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}
onMouseMove={this.handleMouseMove}
title={this.props.option.title}>
<span>Testing Text</span>
{this.props.children}
</div>
);
}
});
How would you pass in more information into this component?
Upvotes: 5
Views: 8612
Reputation: 12029
Well if I am looking at the code correctly it looks like you can pass in an optionRenderer prop along with your optionComponent.
https://github.com/JedWatson/react-select/blob/master/src/Select.js#L874
It takes your option as an argument so hypothetically you can pass additional fields in your option object and render via the optionRenderer function. Maybe something like this...
// ...
optionRenderer(option) {
return (
<div>
{option.value} - {option.label} - {option.someOtherValue}
</div>
)
}
// ...
render() {
let selectProps = {
optionComponent: DropdownOptions,
optionRenderer: this.optionRenderer,
options: this.state.titleResults,
simpleValue: true,
clearable: this.state.clearable,
name: 'selected-state',
value: this.state.selectedTitleValue,
onChange: this.handleTitleChosen,
searchable: this.state.searchable,
autofocus: true
}
return <Select {...selectProps} />
}
Upvotes: 6