Select option with entire object as value
Asked Answered
M

3

6

In my React select input, I want to iterate through my drivers array and for each driver generate the with the single driver as value. But when I console log the target value I have only a [object Object] and if I try to call, for example, driver.driverName I obtain "undefined". Why?

<label className="pt-label pt-inline">
        Autista
        <div className="pt-select">
            <select onChange={this.changeDriver}>
                <option>Scegli autista</option>
                {this.props.drivers.map((driver) => {
                    return <option key={driver.key}
                                   value={driver}>{driver.driverName} {driver.driverLastname}</option>
                                    })}
            </select>
        </div>
</label>
Masorete answered 28/11, 2016 at 15:43 Comment(3)
Can you post the object here too? Or even better can you make a working fiddle?Refund
Create your custom Option component and pass the driver object that component instance as prop. Because "value" attribute accepts string onlyIndependency
I edited my question. Anyway, even with driverName doesn't works.Masorete
M
6

The value of driver is a JS object, but the value attribute of <option> expects a string. Parsing an object to a string in JavaScript will result in [object Object]. You will need to store an individual key value in that space. If you need to pull a specific value from the object when that option is selected, I recommend storing driver.key there and then using that as a lookup reference in your callback function.

Mar answered 28/11, 2016 at 15:47 Comment(0)
M
1

HTML option value does only support string values. You can serialize your object to store it and deserialize it when reading.

Messer answered 28/11, 2016 at 15:47 Comment(0)
R
0

You may stringify you data when set it to value also need to parse it when using the value inside function. Here is an example:

<Input
   type="select"
   value={progressionItem?.rankFrom}
   name="rankFrom"
   onChange={(e) => { setProgressionItem({ ...progressionItem, [e.target.name]: JSON.parse(e.target.value)._id, rankFromName: JSON.parse(e.target.value).rankName })            }} >
                  <option>Select</option>
          {
             ranks.map(rank=><option value={JSON.stringify(rank)} key={rank._id}>{rank.rankName}</option>)
                  }
                </Input>
Ruthenic answered 31/1 at 4:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.