Skip to content
This repository has been archived by the owner on Apr 21, 2023. It is now read-only.

Commit

Permalink
Merge pull request #738 from koba04/forward-ref-examples
Browse files Browse the repository at this point in the history
React.forwardRef accepts a render function, not Functional Component
  • Loading branch information
bvaughn authored Apr 2, 2018
2 parents dbe5b49 + 0ea7d99 commit 4a2a854
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions examples/16-3-release-blog-post/forward-ref-example.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
function withTheme(Component) {
// Note the second param "ref" provided by React.forwardRef.
// We can attach this to Component directly.
// highlight-range{1,5}
function ThemedComponent(props, ref) {
// highlight-next-line
function ThemedComponent({forwardedRef, ...rest}) {
return (
<ThemeContext.Consumer>
{theme => (
<Component {...props} ref={ref} theme={theme} />
// Assign the custom prop "forwardedRef" as a ref
// highlight-next-line
<Component
{...rest}
ref={forwardedRef}
theme={theme}
/>
)}
</ThemeContext.Consumer>
);
}

// These next lines are not necessary,
// But they do give the component a better display name in DevTools,
// e.g. "ForwardRef(withTheme(MyComponent))"
// highlight-range{1-2}
const name = Component.displayName || Component.name;
ThemedComponent.displayName = `withTheme(${name})`;

// Tell React to pass the "ref" to ThemedComponent.
// highlight-next-line
return React.forwardRef(ThemedComponent);
// 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.
// highlight-range{1-3}
return React.forwardRef((props, ref) => (
<ThemedComponent {...props} forwardedRef={ref} />
));
}

// highlight-next-line
Expand Down

0 comments on commit 4a2a854

Please sign in to comment.