Skip to content

Instantly share code, notes, and snippets.

@hg-pyun
Created April 4, 2018 14:05
Show Gist options
  • Save hg-pyun/882874e6446f35ae182d81aa84abd890 to your computer and use it in GitHub Desktop.
Save hg-pyun/882874e6446f35ae182d81aa84abd890 to your computer and use it in GitHub Desktop.
react v16.3.0 medium 05
function withTheme(Component) {
function ThemedComponent({forwardedRef, ...rest}) {
return (
<ThemeContext.Consumer>
{theme => (
// Assign the custom prop "forwardedRef" as a ref
<Component
{...rest}
ref={forwardedRef}
theme={theme}
/>
)}
</ThemeContext.Consumer>
);
}
// Note the second param "ref" provided by React.forwardRef.
// We can pass it along to ThemedComponent as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return React.forwardRef((props, ref) => (
<ThemedComponent {...props} forwardedRef={ref} />
));
}
const fancyButtonRef = React.createRef();
// fancyButtonRef will now point to FancyButton
<FancyThemedButton
label="Click me!"
onClick={handleClick}
ref={fancyButtonRef}
/>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment