1

I have an array like this:

["Daniel", "Adam", "Charlie", "Brad"]

I want to put that array into in react. So i expected the results like this

<select>
    <option> Daniel </option>
    <option> Adam </option>
    <option> Charlie </option>
    <option> Brad </option>
</select>

How I can solve it? Any answer would be appreciated.

1
  • Welcome to Stack Overflow! Please take the tour and read through the help center, in particular How do I ask a good question? Do your research, search for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! Commented Jan 31, 2018 at 6:27

2 Answers 2

2

It's simple. Just map over your array

class App extends React.Component {

      constructor() {
        super();
        this.state = {
          arr: ["Daniel", "Adam", "Charlie", "Brad"]
        }
      }


      render() {
      let {arr} = this.state;
        return (
          <select>
          {arr.map((x, i) => <option key={i}>{x}</option>)}
          </select>
        )
      }

    }

    ReactDOM.render(<App />, document.getElementById('root'));
<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="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

1

you can use map on the array

let a = ["Daniel", "Adam", "Charlie", "Brad"];

<select>
    {
        a.map((item , index) => <option key={index}> {item} </option>)
    }
</select>

4 Comments

Don't forget to have unique key for each option element. Otherwise React will give warning.
@HimanshuArora9419 yes of course
Thank you so much, that is very helpful for beginner like me. :)
you're welcome :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.