Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save paulhhowells/9070dfbd758f5c5777c2299a72cacee4 to your computer and use it in GitHub Desktop.
Save paulhhowells/9070dfbd758f5c5777c2299a72cacee4 to your computer and use it in GitHub Desktop.
/*
react_render_props_with_hooks_and_functional_components.js
Folk write that hooks replace render props, but here they are together!
Why? Because this enables composition of components within mark-up/jsx that share props & state (that has been lifted up).
In this example MyContainer and MyComponent may be reused within other components alongside a variety of extra components.
i.e. MyComponent does not need to be placed within the jsx returned by MyContainer.
*/
import React, { useState } from 'react';
function MyContainer ({ children }) {
const [value, setValue] = useState('Example Value');
return (
<div>
<h2>My Container</h2>
{ children({ value }) }
</div>
);
}
function MyComponent ({ value }) {
return (
<div>
<h3>My Component</h3>
<p>{ value }</p>
</div>
);
}
export const MyPage = () => {
return (
<>
<h1>Example containers</h1>
<MyContainer children={props => (
<MyComponent value={props.value} />
)} />
<MyContainer>
{props => (
<MyComponent value={props.value} />
)}
</MyContainer>
<MyContainer>
{props => (
<MyComponent {...props} />
)}
</MyContainer>
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment