Nick Heidke
Nick Heidke

Reputation: 2847

React Dropdown Not Displaying Options

I have a dropdown created with this statement:

<select
    id="personState"
    name="personState"
    className="form-control dropDownStyle"
    onChange={this.handleChange}
    value={this.props.person.personState}
>
    {this.state.stateCodes.map((option) => {
        <option key={option.id} value={option.data}>{option.data}</option>
    })}
</select>

With the debugger, I can see that this.state.stateCodes is getting populated with a two dimensional array that looks like this:

0:{id: 6408, data: "Arkansas"}
1:{id: 5555, data: "Wisconsin"}

However, no option values are getting added to the dropdown.

Upvotes: 0

Views: 84

Answers (2)

Lee Brindley
Lee Brindley

Reputation: 6512

Your syntax is not quite right, in short, you're not returning the option element.

What you're doing is defining a function body for the anonymous function passed to your map, executing an expression (your element), and returning undefined, as you have no return statement.

Naturally, to fix this you should add a return statement to your function body, or use a more concise syntax for the anonymous function passed to the map.

{this.state.stateCodes.map((option) => {

        //This is the function body, 
        <option key={option.id} value={option.data}>{option.data}</option>

       //We get here and return undefined, as you didn't return above.
    })}

You can use any of the following.

With the return statement. You could wrap the return statement value in parentheses if you wish.

{this.state.stateCodes.map((option) => {
     return <option key={option.id} value={option.data}>{option.data}</option>

})}

Without defining a function body, just defining the value to return.

{this.state.stateCodes.map((option) => <option key={option.id} value={option.data}>{option.data}</option>)}

Upvotes: 1

ramki
ramki

Reputation: 481

You need to return the element inside map callback

{this.state.stateCodes.map((option) => {
    return (
     <option key={option.id} value={option.data}>{option.data}</option>
    )
})}

or just

{this.state.stateCodes.map((option) => (
    <option key={option.id} value={option.data}>{option.data}</option>
))}

Upvotes: 1

Related Questions