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 Toggle Component to a Functional Component with React PowerPlug

    Andrew Del PreteAndrew Del Prete

    In this lesson we'll look at React PowerPlug's Toggle 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 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




    Instructor: I have a simple toggle component. I'll be refactoring to use React PowerPlug. This component consists of state, a handle method to toggle the state true or false, and a render method to toggle between the full moon and the new moon emojis.

    React PowerPlug offers various render less component for common use cases like loaders, lists, and toggles. Let's refactor our example to use the PowerPlug toggle component. First, we'll import the toggle component from React PowerPlug. Since PowerPlug provides the state and logic for us, we'll modify our component to be a functional component instead of a class.

    Next, we'll wrap it with the new toggle component from React PowerPlug. We'll go ahead and give our initial state, the value of true. This means that our toggle will be ON by default. Something to remember is that, all PowerPlug components expect a render property. Toggle provides four properties for us to utilize in our rendered component ON, OFF, Toggle, and SET ON.

    The properties ON and OFF are both Booleans. Toggle is a function to toggle between ON and OFF, and SET ON allows you to specifically set the value ON or OFF. One of our main benefits in this solution is that our state and logic are usable, and completely separate from our UI. In other words, we can literally pass anything we want as a render prop and make it a toggle.

    Let's go ahead and digest that and adjust the render portion of our component and test it out. All right, so it looks like that works. I'm going to change the ternary to ampersands, and show that OFF also works.