Languages

React - how to set state with dynamic key-value pair?

3 points
Asked by:
Wesley
201

I want to dynamically insert key-value pair (from e.g button or input) to the useState object when an event occurs. Does anyone know how to do this?

Short example of what I want to do:

import React from 'react';

const App = () => {
  const [state, setState] = React.useState({});

  const inputChangeHandler = (event) => {
    setState({ event.target.name: event.target.value });
  };

  return (
    <div>
      <div>{JSON.stringify(state, null, 4)}</div>
      <button name="myButton" value={10} onClick={inputChangeHandler}>
        Click me.
      </button>
    </div>
  );
};

export default App;
2 answers
4 points
Answered by:
Wesley
201

Try to use:

setState({ [event.target.name]: event.target.value });

or:

setState({ ...state, [event.target.name]: event.target.value });

You can use that approach for buttoninput and textarea fields.

Preview:

 set state with dynamic key-value pair
 set state with dynamic key-value pair

Code: 

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const [state, setState] = React.useState({});

  const handleFieldChange = (event) => {
    setState({ ...state, [event.target.name]: event.target.value });
  };

  return (
    <div>
      <pre>{JSON.stringify(state, null, 4)}</pre>
      <div style={{ border: '1px solid red' }}>
        <input name="myInput" onChange={handleFieldChange} /><br />
        <textarea name="myTextarea" onChange={handleFieldChange} /><br />
        <button
          name="myButton"
          value="Button value..."
          onClick={handleFieldChange}
        >
          Clikc me!
        </button>
      </div>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
0 comments Add comment
3 points
Answered by:
Wesley
201

I found the solution:

Use array notation to insert event.target.name as property key like this:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const App = () => {
  const [state, setState] = React.useState({});

  const inputChangeHandler = (event) => {
    setState({ [event.target.name]: event.target.value });
  };

  return (
    <div>
      <div>{JSON.stringify(state, null, 4)}</div>
      <button name="myButton" value={10} onClick={inputChangeHandler}>
        Click me.
      </button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

Note:

I also prepared an article on how to update useState object properties with input in React.

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join