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

Already subscribed? Sign In

Autoplay

    Support Control Props for all state

    Kent C. DoddsKent C. Dodds

    Our current implementation of control props only supports controlling the state of a single item of state. Let's make our solution more generic to support any and all state of our component using Object.entries.

    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 and refactor this so it's a little bit more capable. Right now, it only supports the onState, but if your component has more than just a couple items of state, it might be a little tedious to keep this updated.

    00:10 What we are going to do is take our state object and return a new object that combines our controlled and uncontrolled state. Here, we will return objects.entries this.state, and we'll reduce that within arrow function and we'll initialize our reducer with an empty object.

    00:28 The accumulator for this reducer function is going to be our combined state. We'll de-structure each of the entries to their key and value.

    00:37 We will return our combined state and we'll say if this.is controlled key, then our combineStateAtThatKey will equal this.propsAtThatKey. Otherwise, combineStateAtThatKey will be the value because that's coming from state.

    00:57 Now everything is working just as well. This makes our getState function more capable because now it will continue to work regardless of what changes we make to our state.

    Discuss

    Discuss