Nick Heidke
Nick Heidke

Reputation: 2847

Populating React Dropdown Getting Error #31

I've got a bit of Javascript defined as:

populateOptions() {
    var statesMap = [{1: 10}, {2: 20}, {3: 30}];

    return statesMap.map((option, index) => (
        <option key={index} value={option}>{option}</option>
    ));
}

This is called from the render() function:

<div className="col-md-3">
<select name="borrowerState" className="form-control dropDownStyle" onChange={this.handleChange} value={this.props.borrower.borrowerState}>
    {this.populateOptions()}
</select>

When the page attempts to load, I get this in the console:

Error: Minified React error #31; visit https://reactjs.org/docs/error-decoder.html?invariant=31&args[]=object%20with%20keys%20%7B1%7D&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings. at e.exports (invariant.js:42)

Upvotes: 0

Views: 6062

Answers (2)

Manoz
Manoz

Reputation: 6597

On a side note

Since JSON don't parse the values which have key as numeric, it always expects it to be string.

So your JSON still be valid if you change key to string value

Example

enter image description here

However, keys which are not numeric, JSON automatically parse them into string -

var statesMap = [{name: 10}, {name: 20}, {name: 30}];

Like this is going to be parsed automatically because the key is considered to be a string.

Example

enter image description here

I hope its clear.

Upvotes: 0

Anshul Bansal
Anshul Bansal

Reputation: 1893

You are rendering options which is an object inside your select options which is incorrect. You should modify your statesMap and render function as below.

populateOptions() {

        var statesMap = [{'id': 1, 'data': 10}, {'id': 2, 'data': 20}, {'id': 3, 'data': 30}];

        return statesMap.map((option) => (
            <option key={option.id} value={option.data}>{option.data}</option>
        ));
    }

Upvotes: 3

Related Questions