Update arrays and objects using useState Hook in React
This practical and straightforward article shows you how to properly update objects and arrays in the state in React. We'll use the useState hook and functional components.
Without further ado, let’s get started.
When the state is updated, it is completely overwritten. What if our state is an object with multiple properties, but you only want to change the value of a certain property? For example, we initialize the state of the description box like this:
const [box, setBox] = useState({
name: 'jiyik.com',
bgColor: 'blue', // background color
width: 400,
height: 300
});
If you want to change the background color but keep everything else the same, you can use the spread operator (you can also use it with arrays) like this:
setBox(previousState => {
return { ...previousState, bgColor: 'red' }
});
Or like this:
setBox({...box, bgColor: 'red'});
Don't use this code:
setBox({bgColor: 'red'})
Because it removes the name, width and height from the state. To make it clearer, let's dive into the working example below.
Complete Example
App Preview
The demo we're going to make shows a box and several form elements. You can update the box's name, background color, width, or height using the corresponding input/select elements.
Here’s how it works:
step
Following are the steps to build the above demo.
1. Create a new React project:
npx create-react-app jiyik-state-example
The name is entirely up to you. Choose another one if you wish.
2. Final source code in src/App.js (with explanation):
// jiyik.com
// src/App.js
import { useState } from 'react';
import './App.css';
function App() {
// 使用具有四个属性的对象初始化状态
const [box, setBox] = useState({
name: 'jiyik.com',
bgColor: 'blue',
width: 400,
height: 100,
});
// 此函数将更新用户在名称字段中键入时将调用的框的名称
const updateBoxName = (e) => {
setBox({ ...box, name: e.target.value });
};
// 此函数将更新框的背景颜色,当用户更改选择元素时将调用它
const updateBakcgroundColor = (e) => {
setBox({ ...box, bgColor: e.target.value });
};
// 此函数将更新当用户更改宽度输入时将调用的框的宽度
const updateBoxWidth = (e) => {
setBox({ ...box, width: parseInt(e.target.value) });
};
// 此函数将更新当用户更改高度输入时将调用的框的高度
const updateBoxHeight = (e) => {
setBox({ ...box, height: parseInt(e.target.value) });
};
return (
<div style={{ padding: 30 }}>
{/* 这是盒子 */}
<div
style={{
width: box.width,
height: box.height,
background: box.bgColor,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
<h1 style={{ color: '#fff' }}>{box.name}</h1>
</div>
{/* 这是更改框的表单元素 */}
<div
style={{
marginTop: 30,
width: 400,
display: 'flex',
flexDirection: 'column',
}}
>
<h3>Change the Apparence of the Box:</h3>
<p>Box Name:</p>
<input type='text' value={box.name} onChange={updateBoxName} />
<p>Background Color:</p>
<select value={box.bgColor} onChange={updateBakcgroundColor}>
<option value='blue'>Blue</option>
<option value='red'>Red</option>
<option value='green'>Green</option>
<option value='orange'>Orange</option>
</select>
<p>Box Width:</p>
<input type='number' value={box.width} onChange={updateBoxWidth} />
<p>Box Height:</p>
<input type='number' value={box.height} onChange={updateBoxHeight} />
</div>
</div>
);
}
export default App;
}
export default App;
3. Start it:
npm start
And check the result at http://localhost:3000 .
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap