Reputation: 191
I have the following code in a React component:
<select id='header-color'>
{
this.props.colors.map((color, i) => {
return <option
value={color.value}
key={i}
{this.props.headerColor === color.value ? 'selected' : ''}>{color.name}
</option>
})
}
</select>
Eslint is giving me the following error:
Parsing error: Unexpected token, expected "..."
this.props.headerColor is properly passed into the component, and its value should be a string. What am I missing here?
Upvotes: 1
Views: 82
Reputation: 191
Thanks to those who responded. These answers were really helpful, and led me to what I believe is an even better solution.
It seems like React really wants us to handle the state of our select using defaultValue
, with an onChange event handled by a method, like so:
<select id='header-color'
defaultValue={this.props.headerColor}
onChange={this.handleSelectChange}>
{
this.props.colors.map((color, i) => {
return <option value={color.value} key={i}>
{color.name}
</option>
})
}
</select>
For the onChange event, I included this above:
constructor(props) {
super();
this.state = {selectValue: props.headerColor}
this.handleSelectChange = this.handleSelectChange.bind(this);
}
handleSelectChange(e) {
this.setState({selectValue: e.currentTarget.value});
}
Upvotes: 0
Reputation: 112807
selected
is a prop that takes a boolean value. You could change it to the following:
<select id="header-color">
{this.props.colors.map((color, i) => {
return (
<option
value={color.value}
key={i}
selected={this.props.headerColor === color.value}
>
{color.name}
</option>
);
})}
</select>
Upvotes: 3
Reputation: 1275
You need to change your syntax to this:
<select id='header-color'>
{
this.props.colors.map((color, i) => {
return <option
value={color.value}
key={i}
selected={this.props.headerColor === color.value}>
{color.name}
</option>
})
}
</select>
since selected
is a boolean prop rather than a string.
Upvotes: 1