Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In

Autoplay

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

    Andrew Del PreteAndrew Del Prete

    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.

    reactReact
    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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...

    Discuss

    Discuss