Created
November 28, 2020 21:37
-
-
Save getify/699ed762e792bc0942ad692930ec72e4 to your computer and use it in GitHub Desktop.
how to do this in react?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import MyStuffParent from "./my-stuff-parent"; | |
import MyStuff from "./my-stuff"; | |
export default class App extends Component { | |
constructor() { | |
super(); | |
this.state = { | |
showMyStuff: true | |
} | |
} | |
render() { | |
return ( | |
<MyStuffParent> | |
{this.state.showMyStuff && ( | |
<MyStuff | |
stuff={ ** what do I put here? ** } // <------ HERE | |
changeStuff={ ** ditto? ** } // <------ HERE | |
/> | |
)} | |
</MyStuffParent> | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, Fragment } from "react"; | |
export default class MyStuffParent extends Component { | |
constructor() { | |
super(); | |
this.state = { | |
stuff: 42 | |
}; | |
} | |
render() { | |
return ( | |
<Fragment | |
stuff={this.state.stuff} // <------ HERE | |
changeStuff={v => { this.setState({ stuff: v }); }} // <------ HERE | |
> | |
{this.props.children} | |
</Fragment> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component, Fragment } from "react"; | |
export default class MyStuff extends Component { | |
constructor(props) { | |
super(props); | |
this.stuff = props.stuff; | |
this.changeStuff = props.changeStuff; | |
} | |
render() { | |
return ( .. ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I understand correctly, you want to set
stuff
in the children ofMyStuffParent
, and receive aonStuffChange
event when children call that. A few considerations:cloneElement
internally).set
/change
/apply
and so on, it's generally a sign that you aren't using the one-way data flow correctly. You only want value properties, and events (properties prepended byon
).I guess would do it this way:
Cheers!