Skip to content
Advertisement

How do I add an list element seperately to 2 lists?

I am pretty new to react. So I have one parent component which has two child components. These 2 children are the lists that should be displayed. So far I figured out how to transfer the data between two lists by checking the status property of the data. I am not able to understand how to add data into the separate lists and edit them since the parent component renders the 2 lists. Can anyone explain how to add and edit new data that the user will enter? Should I create new states and props on the Items page or should I create them on the child component page? I am pretty confused.

JavaScript

I have attached the 3 components which are Items, Pending and Completed above.

Advertisement

Answer

It’s almost always better to have the state in the parent and pass down props to the children. So you want to keep your items state where it is. You can create an addItem function and pass it down as a prop to any child.


I don’t think it makes sense to be able to add items from both lists since new items should be 'Pending'. So I would recommend that you put your add form in a new component AddItem which would be a third child of Items. Once AddItem calls the addItem function from props, that item will get saved to the state in items and it will show up in the Pending list automatically.

If all new items have status 'Pending' then the only information that we should need to add an item is the title of the task.

This function goes in Items:

JavaScript

Your AddItem component uses a controlled input to create the text for the new item.

JavaScript

Inside the return of Items, include your form:

JavaScript

Unrelated to the question at hand, there are a few other improvements that you can make to your code.

Your updateStatus function actually mutates the current item. You should instead create a new object for the changed item by copying everything except the status.

You are getting warnings about unique keys because the key must be on the outermost component inside the .map(). You put a fragment <> outside the <p> which has the key, so remove the fragment.

In my opinion the filtering of which item goes in each list should be done by the parent. Your Completed and Pending components are extremely similar. You should combine them into one component. Everything that is different between the two, such as texts and class names, can be controlled by the props that you pass in.

JavaScript

Code Sandbox Link

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement