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?

2 Answers 2

1

Just pass a selected attribute to all option tags like this

<option selected={this.props.book.shelf === "read"} value="read">Read</option>
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work for react. See stackoverflow.com/a/21736116/8810941
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

1 Comment

Thanks for the solution.I will give it a try :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.