Home > Back-end >  How to render a dynamic drop down in react?
How to render a dynamic drop down in react?

Time:01-12

I'm trying to render a drop down menu using an array in the state of my react project. It looks like this:

export default class MyTable extends React.Component {
     constructor(props){
          super(props);
          this.state= { list:[1,2,3,4]}
     }

     render() {
          return(
               <div>
                    <select>
                         {this.state.list.map(i => {
                              <option key={i}>{i}</option>
                         })}
                    </select>
               </div>
          );

     }


}

the dropdown is blank though and I can't understand why it's not working???

CodePudding user response:

You are not returning anything from .map loop.

Modified code:

export default class MyTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = { list: [1, 2, 3, 4] };
  }

  render() {
    return (
      <div>
        <select>
          {this.state.list.map((i) => {
            // <option key={i}>{i}</option>; Before
            return <option key={i}>{i}</option>; // Return value here
          })}
        </select>
      </div>
    );
  }
}
  •  Tags:  
  • Related