0

I have a select tag which looks like this:

    <select id="bookName"
     onChange={(event) => this.props.handleShelfChange(this.props.book, event.target.value)}>
        <option value="moveTo" disabled>Move to...</option>
        <option value="currentlyReading">Currently Reading</option>
        <option value="wantToRead">Want to Read</option>
        <option value="read">Read</option>
        <option value="none">None</option>
   </select>

So,here I am receiving props from another component. So, one of the prop is {this.props.book.shelf} .This prop has 4 values :

  1. currentlyReading,
  2. wantToRead,
  3. read and
  4. none.

So, what I want is according to the value that is coming through the props from the parent component, the value of the select option should be selected by default. How can this be done?

mustaccio
  • 18,234
  • 16
  • 48
  • 57
pranami
  • 1,381
  • 5
  • 22
  • 43

2 Answers2

0

Just pass a selected attribute to all option tags like this

<option selected={this.props.book.shelf === "read"} value="read">Read</option>
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37
0

I would suggest component-like approach.

const elems = ['read', 'wantToRead', 'currentlyReading', 'moveTo'];

export default ({ name, value, book: { shelf } }) => (
  <select>
    {elems.map((v) => (
      <Option value={v} selected={shelf} /> // value coming from prop
    ))}
  </select>
);

const Option = ({ value, selected }) => (
  <option value={value} selected={value === selected}>{value}</option>
);

Codesandbox link: https://codesandbox.io/s/x9m9nx5ynp

kind user
  • 40,029
  • 7
  • 67
  • 77