kentcdodds / react-toggled

Component to build simple, flexible, and accessible toggle components
https://codesandbox.io/s/m38674w9vy
MIT License
453 stars 39 forks source link

[Question] Why you used the getOn function instead of React defaultProps? #14

Closed rzkhosroshahi closed 6 years ago

rzkhosroshahi commented 6 years ago

Relevant code or config

What you did:

What happened:

Reproduction repository:

Problem description: Hello, I'm reading your source code. I can't figure out that why you used the getOn function instead of React defaultProps? Please see this my stackblitz Link. What difference between code that you wrote and it's my own code? Thanks. Suggested solution:

newyork-anthonyng commented 6 years ago

@rzkhosroshahi I believe the getOn function is needed so that you can use react-toggled as a controlled or an uncontrolled component. You can read more about it here.

react-toggled manages its own on state automatically (uncontrolled component). However, you can pass in your own on prop to react-toggled and manage its on state manually (controlled component). See the docs for more details.

I updated the StackBlitz example that you had. Notice how I removed the on prop from the <Toggle /> component; the on state still toggles correctly.

However, if you remove the on prop from your <Default /> component, the on state doesn't toggle.

kentcdodds commented 6 years ago

@newyork-anthonyng is correct. If you have an Egghead.io subscription you can watch this video I made about the Control Props pattern :)

kentcdodds commented 6 years ago

No worries @rzkhosroshahi! I'm glad we could help :)

kentcdodds commented 6 years ago

Wut...? Was your email hacked or something @rzkhosroshahi?

rzkhosroshahi commented 6 years ago

Wut...? Was your email hacked or something @rzkhosroshahi?

I can't understand what actually happened. I just signed this "Voices against Sanctions". maybe this email sent for all my contacts as an email but why this email should be here I don't know why. I'm sorry for this @kentcdodds