This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    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.

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

    00:14 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.

    00:40 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.

    01:13 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.

    01:35 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.

    Discuss

    Discuss