Bomber
Bomber

Reputation: 10985

React Js create option list from array

I'm trying to create an options for my select list:

getMarkOptions: function () {
    var options = this.props.renderProps;

    return options.map(function (mark, i) {
        return <option
            key={i}
            value={mark}>
            {mark}
        </option>
    });
},


render: function () {

    console.log('mark editor ' + this.props);

    var selectedMark = this.props.value,
        row = this.props.data,
        highlightCurrentDay = this.props.highlight ? 'edit-select__currentDay':'';
        return (            
            <select
                value={selectedMark}
                ref="selectMark"
                className={"edit-select form-control " + highlightCurrentDay}
                onChange={this.onChange}
            >
                {this.getMarkOptions()}
            </select>      
        );
}

Data:

var marks = [
        {"id": 1, "caption": "/", "code": "/", "meaning": "Present (AM)", "isStandardCode": true},
        {"id": 2, "caption": "\\", "code": "\\", "meaning": "Present (PM)", "isStandardCode": true},
        {"id": 3, "caption": "B", "code": "B", "meaning": "Educated off site", "isStandardCode": true},
        {"id": 4, "caption": "C", "code": "C", "meaning": "Other Authorised Circumstances", "isStandardCode": true},
        {"id": 5, "caption": "D", "code": "D", "meaning": "Dual registration", "isStandardCode": true}
    ];

I keep getting the error:

Unhandled rejection Invariant Violation: Objects are not valid as a React child (found: object with keys {id, caption, code, meaning, isStandardCode}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

Can anyone help?

Upvotes: 2

Views: 6285

Answers (1)

jurassix
jurassix

Reputation: 1519

The invariant is pointing out that the child to the option tag is an object - <option>{mark}</option> - but should be a valid child e.g. string, int, React Component, etc - <option>{mark.meaning}</option>

Try something like this:

return options.map(function (mark, i) {
    return <option
        key={mark.id}
        value={mark.code}>
        {mark.meaning}
    </option>
});

Upvotes: 7

Related Questions