We'll now add another component for rendering a friend. This is the component that we referred to at the end of the last module before the final code block. Now, let's implement it.
Friend
We have the data firing, but we have no way of showing it. We need to show the data in a list. Let's stub out everything we'll need here. We'll code with intent here, thinking about what we'll want to be able to do starting with creating a new file called FriendList.js inside the same directory as FriendListApp.js
All we want this component to do is render each friend. All of the remaining logic that we still need to implement will need to happen back in our FriendListApp component, as we're keeping this one very simple. All we need to do here is figure out how to render each friend. Let's go ahead and do that how we want to. This will be our finished Friend component.
Notice that we're passing two props, one holds the friend information and we're calling it friend, the other is the removeFriend function, that will theoretically remove our friend. We haven't implemented this stuff in our FriendListApp component yet so we need to do that still.
Mapping to Friend
We need to iterate through all of the friends in our state and map them out to our Friend component! This is a very common pattern you'll see in React, where you have a large dataset, and then you map it out into functional components. So here we need to do that. Inside the render, underneath the form add the following:
All we are doing here is mapping our state out to our friend component. Remember when mapping multiples of the same thing, React requires unique key props, so we've added one with id!
Delete Friend
Before, when we created our Friend component we had a removeFriend prop that we used. Let's create that method in our FriendListApp component now. We know based on how we set up Friend that it need to take in an event, and a friend!
Last, we need to update our state. We can do this by filtering out the friend we passed in!
Create the following deleteFriend method in your FriendListApp class, put it underneath and outside of your constructor but above your render!
Now, try it out!! You should be able to add and delete friends!
componentDidMount
You may have noticed, that we have a problem. Try refreshing the app. You should get the form back, but it won't have the data:
Let's fix this! Go to FriendListApp and let's use componentDidMount. Add a fetch request to get our data when our component mounts! This should get our information when we refresh the page!