Become a member
to unlock all features

Level Up!

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


    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.



    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: Let's go ahead and build this toggle component that we're trying to render here, so that I can toggle back and forth. First off, we're going to need to have stateNatWillBeOn as false. The switch component accepts an On prop, so we'll say this.State.On.

    Then we could initialize this to true. That will switch it up to true, but we'll start it out as false.

    We'll also need to pass an onClick, and we'll pass this.Toggle. Toggle will be this arrow function that calls this.setState.

    We need to know what the current state is so that we can update On to be not the current state.On. Cool, now we can toggle it back and forth. Let's go ahead and call the onToggle prop that they're passing us.

    As a callback, we'll call this.props.onToggle, this.State.On. Now we can toggle that back and forth. If we check out our console, we'll see that getting along properly.

    In quick review, to create this component, we rendered the switch with the On and onClick. The On is being managed by the toggle component itself in state, then onClick, the toggle method, will update the state accordingly.

    I'm going to go ahead and refactor this to destructure the current state, so we just grab the On here, and it works just as well.