Use Component State Initializers

Share this video with your friends

Send Tweet

In this lesson, we'll allow users to initialize our component's state with their own defaults and support a reset functionality to reset to the initial state.

Wix
Wix
~ 6 years ago

Hi, Can you elaborate about the case where Toggle is re-rendered with a different value for initialOn?

Erez erezm@wix.com

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

If it's re-rendered with a different value for initialOn then I would consider that to be a mistake on the user's part. If they want to actually change the value that the component gets reset to they can either use a key prop to force react to unmount and remount a new instance, or they can use control props.

Thein
Thein
~ 6 years ago

if multiple buttons with combine behaviors, how will you manage it? For example onoff button plus reset state button?

Thein
Thein
~ 6 years ago

I got it; I can use switch statement at getTogglerProps and use id;

Ann
Ann
~ 6 years ago

Hi, I am confused why you are not using the constructor(props) method to set the initial state. Is this a style preference or is there a benefit to setting it the way you have in this example?

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

We're using public class fields. Learn more about them here: https://egghead.io/lessons/react-use-class-components-with-react and here: https://egghead.io/lessons/javascript-public-class-fields-with-react-components

Thein
Thein
~ 6 years ago

Ann, if you use babel transpiler, at your project root .babelrc file, you can set plugins :["transform-class-properties"]