Skip to content

Commit 4a2a854

Browse files
authored
Merge pull request #738 from koba04/forward-ref-examples
React.forwardRef accepts a render function, not Functional Component
2 parents dbe5b49 + 0ea7d99 commit 4a2a854

1 file changed

Lines changed: 16 additions & 15 deletions

File tree

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

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
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
10+
{...rest}
11+
ref={forwardedRef}
12+
theme={theme}
13+
/>
1014
)}
1115
</ThemeContext.Consumer>
1216
);
1317
}
1418

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);
19+
// Note the second param "ref" provided by React.forwardRef.
20+
// We can pass it along to ThemedComponent as a regular prop, e.g. "forwardedRef"
21+
// And it can then be attached to the Component.
22+
// highlight-range{1-3}
23+
return React.forwardRef((props, ref) => (
24+
<ThemedComponent {...props} forwardedRef={ref} />
25+
));
2526
}
2627

2728
// highlight-next-line

0 commit comments

Comments
 (0)