Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary in jsx to add selected attribute to option

Tags:

reactjs

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>
like image 853
Bomber Avatar asked Sep 18 '25 16:09

Bomber


1 Answers

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'/>
like image 140
Mayank Shukla Avatar answered Sep 20 '25 06:09

Mayank Shukla