Autoplay

    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.

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

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

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

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

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

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

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

    Discuss

    Discuss