Last updated: Apr 6, 2024
Reading timeยท2 min
Use square bracket notation to set and access state using a dynamic key in React.
The variable or expression in the square brackets will be evaluated before the state is set.
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;
We wrapped the dynamic key in square brackets in order to evaluate it when updating the state.
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.
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.
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.
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.
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;
You can learn more about the related topics by checking out the following tutorials: