Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




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

    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.

    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.

    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.

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