Skip to content

Commit d5c449d

Browse files
committed
React.forwardRef accepts a render function, not Functional Component
1 parent e864607 commit d5c449d

1 file changed

Lines changed: 12 additions & 15 deletions

File tree

examples/16-3-release-blog-post/forward-ref-example.js

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,24 @@
11
function withTheme(Component) {
2-
// Note the second param "ref" provided by React.forwardRef.
3-
// We can attach this to Component directly.
4-
// highlight-range{1,5}
5-
function ThemedComponent(props, ref) {
2+
// highlight-next-line
3+
function ThemedComponent({forwardedRef, ...rest}) {
64
return (
75
<ThemeContext.Consumer>
86
{theme => (
9-
<Component {...props} ref={ref} theme={theme} />
7+
// Assign the custom prop "forwardedRef" as a ref
8+
// highlight-next-line
9+
<Component {...rest} ref={forwardedRef} theme={theme} />
1010
)}
1111
</ThemeContext.Consumer>
1212
);
1313
}
1414

15-
// These next lines are not necessary,
16-
// But they do give the component a better display name in DevTools,
17-
// e.g. "ForwardRef(withTheme(MyComponent))"
18-
// highlight-range{1-2}
19-
const name = Component.displayName || Component.name;
20-
ThemedComponent.displayName = `withTheme(${name})`;
21-
22-
// Tell React to pass the "ref" to ThemedComponent.
23-
// highlight-next-line
24-
return React.forwardRef(ThemedComponent);
15+
// Note the second param "ref" provided by React.forwardRef.
16+
// We can pass it along to ThemedComponent as a regular prop, e.g. "forwardedRef"
17+
// And it can then be attached to the Component.
18+
// highlight-range{1-3}
19+
return React.forwardRef((props, ref) => (
20+
<ThemedComponent {...props} forwardedRef={ref} />
21+
));
2522
}
2623

2724
// highlight-next-line

0 commit comments

Comments
 (0)