Michael
Michael

Reputation: 1714

How can I create a drop down list from a state array?

I'm currently trying to render a drop down list within react that will display a list of times. The user should be able to select a specific value and that value will get updated within the state via onChange(). My issue is that I'm trying to use select, but my drop down list is not showing anything when I click on it. Any help would be appreciated, thanks.

This is what I have currently

myfile.js


export default class MyClass extends Component {
    constructor(props){
    super(props);

    this.state = {

    times: ["1:00", "2:00", "3:00"]

    }
}

RenderList(){
 let tempArray = [];
   let times = this.state.times;

        for(var i = 0; i < times.length; i++){
           tempArray.push(<option>{times[i]}</option>)
        }

        return tempArray
}

return (
<div
  <select>{this.RenderList()}</select>
</div>
);

}

I kind of expected to see a list of times in the drop down list once it was rendered, but the list is null.

Upvotes: 1

Views: 6982

Answers (2)

Shmili Breuer
Shmili Breuer

Reputation: 4147

I think I would do it this way.

import React, {Component} from 'react'

class ComponentName extends Component{
    state = {
        myArray: ["1:00", "2:00", "3:00"]}
    }


     render() {
         return (
             <select>
                 {this.state.myArray.map(optn => (
                     <option>{optn}</option>
                 ))}
             </select>
         )
     }

     export default ComponentName

Hope this helps

Upvotes: -1

German
German

Reputation: 557

Is this what you are looking for? You need map to render the options, I hope this helps!

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      times: ["1:00", "2:00", "3:00"]
    }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(e) {
    console.log(e.target.value)
  }

  render() {
    const {times} = this.state;
    return (
      <select onChange={this.handleChange}>
         {times.map(time => {
           return (
             <option value={time}> {time} </option>
           )
         })}
    </select>
    )
  }
}
render(<App />, document.getElementById('root'));

Upvotes: 2

Related Questions