Photo by RetroSupply on Unsplash
Day 12 of 100days of code.
Hello and welcome to day 12 of my challenge.💪💪💕
Table of contents
Lifting State up in practice.
So, from our previous travel list app, we needed to find a way to render the newItem
created in the packingList
component and be able to map over this to display the list, instead of the dummy intialItem
list created. Thus, it sounds like we need data, and since this data will re-render, we need to create a state in Form
called items
. Since the dummy intialItem
is an array, we set the state variable to a default value of an empty array.👇👇
Next, I'll create a handleAddItem
function that adds an item to the existing item array. For this, I'll spread the existing array and add the new items. Note that we cannot simply use push
on the state, as doing so would result in mutating the state👇👇.
Now, we call the handleAddItem
function in the handleSubmit
function, passing newItem
as an argument at line 26 👇👇👇
Now, the handleAddItem
function works perfectly as it adds a new item to the array. Take note of how the developer console looks before adding a new item
Let's try adding a new item by specifying the quantity and the item to be added, which, in our case, is a toothbrush👇
Check the result in the developer tools👇👇
Now we need to figure out a way to display the items array in the component where it is needed, specifically in the PackingList
component. Additionally, it's worth noting that the handleAddItem
function is required by the Form
component, while the items array is necessary for the PackingList
component. To address this, we should lift the state up to their common parent, which in our case is the App
component.
This is how the App
component looks previously👇👇
And now, after lifting the state, it looks like👇. Now we can pass the items array and the function as props to both the PackingList
and Form
components
Here, we destructure the onAddItem
function and make it available for the Form
component👇
This is the initial state of the PackingList
component👇
Now, we utilize the items
array instead of the initialItems
array and map through it in the PackingList
component👇
Adding a newItem
now includes it in the PackingList
component👇
Thank you for reading..