Become a member
to unlock all features

Level Up!

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


    Advanced React Component Patterns Update

    Build a Toggle Component


    In this lesson, we’ll write a simple toggle component which will serve as the foundation for the rest of the course. Kent walks through how to create a simple toggle with React setState. He shows us how to extend the functionality of the toggle by safely adding an onToggle prop that gets called after state is updated. It is important to define default props when you are calling a method from props.



    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: We're rendering this switch component. We can change this from false to true to turn it on and then back to false to turn it off. But we want to be able to click on it to toggle that state. We need to keep that state somewhere and update the on state.

    Let's go ahead and make a React component called toggle. Here we'll move this return statement to that. We'll render toggle instead. So far, that gets us exactly what we had before. Now we need to store that state somewhere. We'll say state on is false to initialize that. Then we'll get the state of on from this.state. We'll put on in here.

    Then we need a way to update that state. We'll make a toggle function here. That will call this.set state. We need to know what the on state currently is so that we can toggle it off. Then, in our switch component, we'll add an on click. This will pass in this.toggle. With that, we can click. It toggles on and off.

    Finally, just to make things a little bit more extensible, we're going to add a callback function here that will call this.props.on toggle with this.state.on. With that, we can add on toggle equals on alert on. We get true and false.

    One last thing, since we added this on toggle prop, if we go ahead and remove that and then try to click, it breaks our entire app. That's because it's calling a function that doesn't exist. Let's go ahead and add...thetic default props on toggle is just an empty function that does nothing. Now if we click this, it still works. But nobody knows that the toggle is changed.

    We're going to go ahead and add on toggle with on console.log toggle on. Now if we pull up our dev tools, we get that logged to the console...