Last updated on Oct 2, 2020 by Suraj Sharma
In this tutorial, you will learn how you can add an item to a stateful Array in React.
Consider, we have a function component ItemList
that has a list of users as a local state,
as discussed in this tutorial.
const userList = [
{
id: 1,
username: 'surajy2j',
name: 'Suraj'
},
{
id: 2,
username: 'nilesh20',
name: 'Nilesh'
}
];
const ItemsList = () => {
const [users, setUsers] = React.useState(userList);
return (
<ul>
{users.map(user=>(
<li
key={user.id}
>
{user.username}
</li>
))}
</ul>
)
}
export default ItemList;
<Button variant="primary" onClick={handleAddUser}>
Add User
</Button>
On click of a button, we are going to add a new user to the users
state using the Array.concat()
method.
You can even use the JavaScript spread(...) operator, both of them create a new array.
We call the setUsers function to create a new ‘users’ state from the previous state.
const handleAddUser = () =>{
setUsers((state)=>[...state, {id: 3, username: 'max123', name: 'Maxwell'}])
// or state.concat([{id: 3, username: 'max123', name: 'Maxwell'}])
}
This renders a new li
element on the browser on click of the button.
The complete code looks like this
const ItemsList = () => {
const [users, setUsers] = React.useState(userList);
const handleAddUser = () =>{
setUsers((state)=>[
...state,
{id: 3, username: 'max123', name: 'Maxwell'}
]);
// Or state.concat([{id: 3, username: 'max123', name: 'Maxwell'}])
}
return (
<>
<ul>
{users.map(user=>(
<li
key={user.id}
>
{user.username}
</li>
))}
</ul>
<Button variant="primary" onClick={handleAddUser}>
Add User
</Button>
</>
)
}
export default ItemList;
Related Solutions
How to build a react login form with Typescript and React hooks
How to Disable a Button when an Input field is Empty in React
How to conditionally render React components using React hooks
Rate this post
Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.