Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to render a dynamic drop down in react?

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???

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
    );
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading