File tree Expand file tree Collapse file tree 2 files changed +45
-12
lines changed Expand file tree Collapse file tree 2 files changed +45
-12
lines changed Original file line number Diff line number Diff line change 2
2
* @jest -environment jsdom
3
3
*/
4
4
5
- import { PropsWithChildren } from "react" ;
5
+ import { Component , createRef , PropsWithChildren } from "react" ;
6
6
import { createRoot } from "react-dom/client" ;
7
7
import { act } from "react-dom/test-utils" ;
8
8
import { withErrorBoundary } from "./withErrorBoundary" ;
@@ -53,4 +53,28 @@ describe("withErrorBoundary", () => {
53
53
render ( ) ;
54
54
expect ( container . textContent ) . toBe ( "Error" ) ;
55
55
} ) ;
56
+
57
+ it ( "should forward refs" , ( ) => {
58
+ type Props = { foo : string } ;
59
+
60
+ class Inner extends Component < Props > {
61
+ test ( ) { }
62
+ render ( ) {
63
+ return this . props . foo ;
64
+ }
65
+ }
66
+
67
+ const Wrapped = withErrorBoundary ( Inner , {
68
+ fallback : < div > Error</ div > ,
69
+ } ) ;
70
+
71
+ const ref = createRef < Inner > ( ) ;
72
+
73
+ act ( ( ) => {
74
+ root . render ( < Wrapped foo = "abc" ref = { ref } /> ) ;
75
+ } ) ;
76
+
77
+ expect ( ref . current ) . not . toBeNull ( ) ;
78
+ expect ( typeof ref . current ?. test ) . toBe ( "function" ) ;
79
+ } ) ;
56
80
} ) ;
Original file line number Diff line number Diff line change 1
- import { ComponentType , createElement } from "react" ;
1
+ import {
2
+ createElement ,
3
+ forwardRef ,
4
+ ForwardedRef ,
5
+ RefAttributes ,
6
+ ForwardRefExoticComponent ,
7
+ PropsWithoutRef ,
8
+ ComponentType ,
9
+ } from "react" ;
2
10
import { ErrorBoundary } from "./ErrorBoundary" ;
3
11
import { ErrorBoundaryProps } from "./types" ;
4
12
5
13
export function withErrorBoundary < Props extends Object > (
6
- Component : ComponentType < Props > ,
14
+ component : ComponentType < Props > ,
7
15
errorBoundaryProps : ErrorBoundaryProps
8
- ) : ComponentType < Props > {
9
- const Wrapped : ComponentType < Props > = ( props : Props ) => {
10
- return createElement (
11
- ErrorBoundary ,
12
- errorBoundaryProps ,
13
- createElement ( Component , props )
14
- ) ;
15
- } ;
16
+ ) : ForwardRefExoticComponent < PropsWithoutRef < Props > & RefAttributes < any > > {
17
+ const Wrapped = forwardRef < ComponentType < Props > , Props > (
18
+ ( props : Props , ref : ForwardedRef < ComponentType < Props > > ) =>
19
+ createElement (
20
+ ErrorBoundary ,
21
+ errorBoundaryProps ,
22
+ createElement ( component , { ...props , ref } )
23
+ )
24
+ ) ;
16
25
17
26
// Format for display in DevTools
18
- const name = Component . displayName || Component . name || "Unknown" ;
27
+ const name = component . displayName || component . name || "Unknown" ;
19
28
Wrapped . displayName = `withErrorBoundary(${ name } )` ;
20
29
21
30
return Wrapped ;
You can’t perform that action at this time.
0 commit comments