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.

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
Rama Widi
  • 53
  • 1
  • 1
  • 10
  • Welcome to Stack Overflow! Please take the [tour] and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Do your research, [search](/help/searching) 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 [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder Jan 31 '18 at 06:27

2 Answers2

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>
Ahsan Ali
  • 4,951
  • 2
  • 17
  • 27
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>
Ali Faris
  • 17,754
  • 10
  • 45
  • 70