How to add an item to a list in React

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;


Add an item to the list


<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 to add an item to the list


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


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.