Refactor a Stateful List Component to a Functional Component with React PowerPlug

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 3 years ago

In this lesson we'll look at React PowerPlug's List component by refactoring a normal class component with state and handlers to a functional component powered by React PowerPlug.

Instructor: [00:00] I have a React component that shows a list of names. By each name, there's an X to remove it. I also have a button to add a random name to the list. This component contains a state to hold the array of names, a handler to add an item to the list, and another handler to remove an item from the list.

[00:20] Let's go ahead and simplify this by using the list component that's included with React PowerPlug. We'll first need to import it. Because React PowerPlug handles the state and logic for us, let's modify our existing component to be a functional, or stateless component. I'll remove state and our handler methods to clean this up for us.

[00:45] Next, we'll go ahead and wrap our component with the list component and give it some initial values. All React PowerPlug components use the render prop pattern to extract away common state and logic requirements we may run into on a day-to-day basis.

[01:00] The list component provides several properties to make our jobs easier, List, Push, Pull, Sort, and Set List. We'll be using List, Push, and Pull for this example. List is our array of items. Push allows us to add a new item to that list. Pull removes an item from the list. Now, to refactor our render method to use the new functionality provided by the list component. This .state.names becomes List.

[01:38] Handle Delete is replaced by Pull, which acts like a filter method where we can compare each name in a list with a name we provide, and remove it if matches. Finally, Handle Add is replaced by invoking Push and passing in a value...

Andrew Del Prete
Andrew Del Preteinstructor
~ 7 years ago

There's a small typo in my video. I have a few class references that should className. Still works though 👍🏼

Markdown supported.
Become a member to join the discussionEnroll Today