Search code examples
javascriptreactjssetstate

Using a dynamic key to setState in React


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.


Solution

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

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