Make components reusable in React with a flexible props API

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

In this lesson, we abstract a reusable NamesList component, that will render the same JSX in two different scenarios. We keep the logic of the onClick event outside of the component, and pass it as a callback prop.

Simon Vrachliotis: [0:00] Let's build a proper UI for the ShortList now. It looks like what we want is very similar to the JSX in the NamePicker component, but we'll need a different behavior when the name is clicked. If we look at the JSX, we have an unordered list that takes a list of names, iterates over them and then outputs each name in a list item.

[0:19] The logic for what happens when the user clicks on these names should probably pass as a prop instead of living in that component. Sounds like we can refactor this in the NameList component which can take two props, a nameList prop for the array of names and an onItemClick to handle the logic to follow when a user clicks on a name.

[0:40] Let's create a new component called NameList.js. Import React and export a function called NameList() which takes a nameList and an onItemClick props.

[0:55] We'll copy over the JSX from the NamePicker in the return statement. Instead of filteredNames, we can use our nameList prop here to iterate over. Instead of addToShortList, we'll use our onItemClick callback.

[1:11] Let's go back to our NamePicker component and import our NameList components. We can now replace the unordered list here with a call to NameList, and we'll pass nameList = filteredNames, and onItemClick = addToShortList. Nice, it still works.

[1:34] Let's tackle the ShortList component now. We'll import the NameList component here too. In the return statement, we'll wrap our JSX in a div with a className of short-list for styling purposes. Let's pass the names from App.js as a prop.

[2:02] To get a shortListedNames list, we will filter over the names array and keep the entries where the shortList includes the entry.id.

[2:12] We will also create a removeFromShortList() function here, that can be passed as an onItemClick prop. This function will update the ShortList accordingly, setShortList. We want to set that to the current shortList minus the id that was passed.

[2:29] We can achieve that with a filter, again, removing the id that matches.

[2:44] Nice. It all works. We now are using the same UI component in two different places without duplication.

[2:52] Quick aside, this component makes the assumption that the correct props are being passed to it. We're not doing it here, but this would be a good place to use prop types or a type system like TypeScript or Flow to guard against implementation errors in your application.