Home > Net >  How I can use <select> in form in react app?
How I can use <select> in form in react app?

Time:01-28

I am a beginner. I want to create a form with a "select" field which would have as an option a list of categories in the database. This is a react app. The file is a register.js I made it in .ejs with a for loop but I don't know how to translate it into js. Thank you for your answers.

    <select name="category">
    <% for(let i = 0; i < categories.length; i  ) { %>
        <option value="<%=categories[i].Id%>"><%=categories[i].Name%></option>
    <% } %>
    </select>

CodePudding user response:

If I'm understanding correctly and your categories are set up in an array, you can use the fact that React is capable of rendering arrays of JSX to implement the following between the select tags:

{categories.map(category => <option key={category.Id} value={category.Id}>{category.Name}</option>)}

You may have to change it to fit how you've structured your categories array, but as long as it's an array something like this should work. Every time you see braces here, we're dropping into JavaScript from JSX. If there's anything that doesn't make sense about this, let me know.

EDIT: Note that, as Carlos Lombardi pointed out, this all has to be returned from a React component function that is being called as its own component within the App.

EDIT 2: Thanks to Peter J Langley for pointing out that it's best to use a key here. If you know your Id properties are unique, then that seems like a natural choice for your key values.

  •  Tags:  
  • Related