Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dynamic key to setState in React [duplicate]

From an input field I am sending the value as an argument to the function that sets state. I have multiple input fields so would like to use their name (which is equal to their state key) to then use the same function and pass in the key and value to the function that sets state.

here is my code.

<Modal
  onTextChange={(text, key) => {
    this.setState({
      event: {
        key: text
      }
    })
  }}
/>

and the input

<input
  type="date"
  name="dateStart"
  onKeyUp={event => this.props.onTextChange(event.target.value, event.target.name)
/>

the text argument works, but the key argument does not.

Thanks in advance.

like image 342
Middi Avatar asked Jan 18 '26 11:01

Middi


1 Answers

When setting state with a dynamic key, you need to wrap the key within [] like

<Modal
  onTextChange={(text, key) => {
    this.setState({
      event: {
        [key]: text
      }
    })
  }}
/>
like image 153
Shubham Khatri Avatar answered Jan 21 '26 00:01

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!