|
1 | 1 | 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}) { |
6 | 4 | return ( |
7 | 5 | <ThemeContext.Consumer> |
8 | 6 | {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} /> |
10 | 10 | )} |
11 | 11 | </ThemeContext.Consumer> |
12 | 12 | ); |
13 | 13 | } |
14 | 14 |
|
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 | + )); |
25 | 22 | } |
26 | 23 |
|
27 | 24 | // highlight-next-line |
|
0 commit comments