Previously we learned how to render a list of items in React. Today we’ll be focusing on adding items to the list. The idea is to show that React will recognise these changes as the list changes and update the UI accordingly.
Our previous example used an array with three items in it:
const [listData, setListData] = useState([
'Item 1',
'Item 2',
'Item 3',
/* Add more items as needed */
]);
That example was enough to display the data, but we never used the setListData
function.
This function will take an array as input and update the value of listData
(after the next render) in our component.
You might want to add items to the list in three ways. One, by adding to the end of the list. Two, inserting a new item or items in the middle of the list. Or three, by inserting items at the start of the list. I’ll cover off these three ways below.
Important: Don’t Alter State Directly
In React, you don’t directly alter state variables. Doing so will mess with Reacts internal system of managing state and props. If you were to manually change the items in the list you will end up with unpredictable results. Always use a React function to update your state.
Having said that, let’s cover ways to add items to a list.
Adding Items To The End Of The List
If you wanted to add items to an array in Javascript, you could use the push method to add what you need. But this would alter the array, which we don’t want to do in React.
One way to achieve this would be to use concat function:
const originalArray = [1,2,3];
const additionalArray = [4,5,6];
const newArray = originalArray.concat(additionalArray);
// now you can set the state with the newArray
setArray(newArray);
This would do the trick, but Javascript has this neat thing called the spread operator. Using spread syntax, we can still achieve the intended result in a short amount of code.
const originalArray = [1,2,3];
const additionalArray = [4,5,6];
const newArray = [...originalArray, ...additionalArray];
// now you can set the state with the newArray
setArray(newArray);
WARNING: The spread operator only takes a shallow copy of the arrays you are merging. This means that if one of the arrays contains nested arrays or objects then the resulting array will be contain references to the original objects.
Inserting Items Into The List
Inserting items into an array can be done using slice and the spread syntax. Let’s look at an example of how this works:
const myList = [1, 2, 3, 4, 5];
const newItem = 10;
const indexToInsert = 2;
// Using spread syntax to insert the newItem into the middle of the list
const updatedList = [...myList.slice(0, indexToInsert), newItem, ...myList.slice(indexToInsert)];
console.log(updatedList); // Output: [1, 2, 10, 3, 4, 5]
The updatedList
constant is created by taking a slice of the original list myList
up until the insertion index (2). From here, we add the newItem
and finally the end slice of the array.
Using this method we have not mutated our original list
Prepend Items To A List
We’ve already seen how to use the spread syntax to add items to the end of the array. You can use the same technique to add items to the beginning of the array. All we have to do is swap the array arguments to put the new items before the original ones.
const originalArray = [1,2,3];
const itemsToAddBeforeOriginalArray = [4,5,6];
const newArray = [...itemsToAddBeforeOriginalArray , ...originalArray];
// now you can set the state with the newArray
setArray(newArray);
And that is how you can add items to your lists in React. Don’t forget to check out my other React articles here.
You can follow me on Twitter here