3

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.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
Middi
  • 343
  • 1
  • 3
  • 12

1 Answers1

8

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

<Modal
  onTextChange={(text, key) => {
    this.setState({
      event: {
        [key]: text
      }
    })
  }}
/>
Tholle
  • 108,070
  • 19
  • 198
  • 189
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400