I am using the following code to add selected to an option:
<select name="hourSelect" ref="hourSelect">
{hourSelect.map((option) => (
<option value={option.value} {(selectedHour == option.value) ? 'selected' : ''}>{option.label} </option>
))}
</select>
I getting the syntax error: Syntax error: C:/sites/CalendarRedux/src/components/modals/AddAchievementModal.js: Unexpected token, expected ... (94:52)
92 | <select name="hourSelect" ref="hourSelect">
93 | {hourSelect.map((option) => (
> 94 | <option value={option.value} {(selectedHour == option.value) ? 'selected' : ''}>{option.label} </option>
| ^
95 | ))}
96 | </select>
Assign the value true or false to selected
property (missed the property name), like this:
<option value={option.value} selected = {selectedHour == option.value ? true : false}>{option.label} </option>
I will suggest you to use the controlled component by using the value property of select
and maintain that value by state
variable.
Check the working snippet:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render(){
return(
<select onChange={e => {}}>
<option value='1' disabled>Select</option>
{
[2,3,4].map((i,j)=>{
return <option selected={i == 2 ? true : false} key={i} value={i}>{i}</option>
})
}
</select>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With