Mahdi
Mahdi

Reputation: 1405

how can I get access to the key in react?

I have a code like this :

counter = 0,
this.props.array.map((obj)=>{
    counter++
    return(
        <input key={counter} type="number" min={0} defaultValue={obj.quantity} onChange={(e)=>{this.changing(key, counter)}}/>
    )
})
changing = (value, key)=>{
    console.log(key + ' changed')
}

as you can see I used 'key' in the bad place and it doesn't work at all

and also if I use 'counter' instead of 'key' it always returns the latest 'counter'

Please tell me how I can get access to the key in the element

Upvotes: 0

Views: 38

Answers (1)

John Ruddell
John Ruddell

Reputation: 25862

You should use the index in the array as you map. not store a counter

this.props.array.map( (obj, idx)=>{
    return(
        <input key={idx} type="number" min={0} defaultValue={obj.quantity} onChange={this.changing.bind(null, idx)}}/>
    )
})
// notice i changed your handler for change. You should use `.bind` not an inline arrow as its not as performant as `.bind`

changing = (key) => {
    console.log(key + ' changed')
}

I feel like this is not what you want though. Are you trying to figure out the key so you know what to update in your storage? What are you trying to accomplish here?

Upvotes: 1

Related Questions