Last active
November 25, 2018 04:17
-
-
Save kilgarenone/8b53640ce3ed3d636ef446f4d6603a93 to your computer and use it in GitHub Desktop.
react render props
This file contains hidden or 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
// Function as children pattern | |
// Notice below that the body/children of <Hello /> is a anonymous function definition! | |
<Hello> | |
{ (foo) => (<World foo={foo} />) } | |
</Hello> | |
/* | |
And then we execute the function - this.props.children(), | |
while passing it the 'foo' data as an argument to the function above- | |
(foo) => (<World foo={foo} />), giving us whatever view is rendered inside the <World />! | |
*/ | |
class Hello extends React.Component { | |
state = { foo: 123 } | |
/* stuffs */ | |
render() { | |
return ( | |
{ this.props.children(this.state.foo) } | |
) | |
} | |
} | |
/* Another render props pattern is passing our function to a component's prop */ | |
// A function is passed to a prop named in this case 'render' but could be any name like any other prop! | |
<Hello render={ (foo) => (<World foo={foo} />) } /> | |
/* | |
So since the function was passed to a prop named 'render', the only difference | |
than before is that, instead of 'this.props.children', we are accessing the props object for | |
'render' prop- this.props.render | |
*/ | |
class Hello extends React.Component { | |
state = { foo: 123 } | |
/* stuffs */ | |
render() { | |
return ( | |
// notice we are just accessing the 'render' prop in our typical 'props' object | |
{ this.props.render(this.state.foo) } | |
) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment