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
Become a member
to unlock all features

    Advanced React Component Patterns Update

    Build a Toggle Component

    Kent C. DoddsKent C. Dodds

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

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

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

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

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

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