Munsterberg
Munsterberg

Reputation: 828

setState with <select> options with values as objects

I have a component that renders a select element like so:

<select 
    name="directoryAttributes"
    id="dirSelect"
    className="form-control"
    onChange={this._handleChange}>
    {
        attributes.map(attribute => {
            return (
                <option
                    value={attribute}
                    key={attribute.directoryAttributesNo}
                >{attribute.label}</option>
            );
        })
    }
</select>

attribute is a plain object with some key/values. I want to call a handleChange to set my components state to that option value (i.e. attribute object). Here is my handleChange

_handleChange(e) {
    e.preventDefault();
    const element = e.target;
    const stateObject = {};

    stateObject[element.name] = element.value;
    this.setState(stateObject);
}

The issue is, it appears to set the state of directoryAttributes to [object Object]. Why is this happening, is it a quirk of react or something im missing?

Thanks in advance!

EDIT: the attributes array of objects comes from the state, just to clarify

Upvotes: 0

Views: 2013

Answers (2)

holi-java
holi-java

Reputation: 30686

you can't but you can use an unique id ref the props in the parent Component.

 <select name="directoryAttributes" id="dirSelect" className="form-control" onChange={this._handleChange}>
            {
                attributes.map(attribute => {
                    return (
                        <option
                            value={attribute.directoryAttributesNo}
                            key={attribute.directoryAttributesNo}
                        >
                                {attribute.label}
                        </option>
                    );
                })
            }
        </select>

then filter the attribute from attributes.

_handleChange(e) {
   e.preventDefault();
   const element = e.target;
   const stateObject = {};

   stateObject[element.name] = getAttributeById(element.value);
   this.setState(stateObject);
}

Upvotes: 2

mahieus
mahieus

Reputation: 580

The problem is that you can't set an object as the value of the option of your select. The value will be set the the string value [object Object].

What you can do is do a look up in your attributes based on the id.

Upvotes: 5

Related Questions