Set and Access state using a Dynamic key in React

avatar

Borislav Hadzhiev

Mon Apr 18 20222 min read

banner

Photo by Daniel Cano

Set and Access state using a Dynamic key in React #

Use square bracket notation to set and access state using a dynamic key in React, e.g. setEmployee({...employee, [key]: employee.salary + 100}). The variable or expression in the square brackets will get evaluated before the state is set.

App.js
import {useState} from 'react'; const App = () => { const [employee, setEmployee] = useState({id: 1, name: 'Alice', salary: 100}); const key = 'salary'; // ✅ access state using dynamic key console.log(employee[key]); // 👉️ 100 const handleClick = () => { // ✅ set state using dynamic key setEmployee({...employee, [key]: employee.salary + 100}); }; return ( <div> <button onClick={handleClick}>Increase salary</button> <h2>id: {employee.id}</h2> <h2>name: {employee.name}</h2> <h2>salary: {employee.salary}</h2> </div> ); }; export default App;

react usestate dynamic key

We wrapped the dynamic key in square brackets in order to evaluate it when updating the state.

The key variable will get evaluated to salary and the value of the salary property will get updated in the state object.

Note that this syntax is not React.js specific, this is plain JavaScript.

App.js
const emp = {id: 2, name: 'Bob', salary: 100}; const key = 'salary'; console.log(emp[key]); // 👉️ 100 const newEmp = { [key]: 200, // 👈️ using dynamic key }; console.log(newEmp); // 👉️ {salary: 200}

You can also use logic or concatenate strings to form the dynamic key.

App.js
const start = 'sal'; const end = 'ary'; const newEmp = { [start + end]: 200, }; // 👉️ {salary: 200}

In the same way, you can call a function to get the dynamic key.

App.js
function getKey() { return 'salary'; } const newEmp = { [getKey()]: 200, }; console.log(newEmp); // 👉️ {salary: 200}

The syntax for setting the state of a React component using a dynamic key is the same.

App.js
import {useState} from 'react'; const App = () => { const [employee, setEmployee] = useState({id: 1, name: 'Alice', salary: 100}); const handleClick = () => { function getKey() { return 'salary'; } // 👇️ call function to get dynamic key setEmployee({...employee, [getKey()]: employee.salary + 100}); }; return ( <div> <button onClick={handleClick}>Increase salary</button> <h2>id: {employee.id}</h2> <h2>name: {employee.name}</h2> <h2>salary: {employee.salary}</h2> </div> ); }; export default App;
Use the search field on my Home Page to filter through my more than 1,000 articles.