Skip to content
This repository was archived by the owner on Oct 23, 2023. It is now read-only.

Commit a45be11

Browse files
authored
fix: forward ref type (#34)
* fix(react): forward ref typings * test(react): add tests for forward ref
1 parent f8eafa4 commit a45be11

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

packages/react/src/forwardRef.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ export function forwardRef<
6363
Props extends Record<string, unknown> = Record<never, never>,
6464
>(
6565
component: ForwardRefRenderFunction<
66-
unknown,
67-
AssignCommon<ComponentProps<Component>, Props> & {
66+
never,
67+
AssignCommon<PropsOf<Component>, Props> & {
6868
as?: ElementType
6969
}
7070
>,
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { createRef } from 'react'
2+
import type { HTMLPolymorphicProps } from '../src'
3+
import { polymorphicFactory, forwardRef } from '../src'
4+
import { render } from '@testing-library/react'
5+
6+
describe('forwardRef', () => {
7+
const poly = polymorphicFactory()
8+
9+
it('should forward the ref', () => {
10+
const ComponentUnderTest = forwardRef<'div', HTMLPolymorphicProps<'div'>>((props, ref) => (
11+
<poly.div {...props} ref={ref} />
12+
))
13+
14+
const ref = createRef<HTMLDivElement>()
15+
render(<ComponentUnderTest ref={ref} />)
16+
expect(ref.current).toBeInstanceOf(HTMLDivElement)
17+
})
18+
19+
it('should forward the ref with as prop', () => {
20+
const ComponentUnderTest = forwardRef<'div', HTMLPolymorphicProps<'div'>>((props, ref) => (
21+
<poly.div {...props} ref={ref} />
22+
))
23+
24+
// known issue: with the `as` prop refs are not inherited correctly
25+
// workaround:
26+
const ref = createRef<HTMLDivElement & HTMLFormElement>()
27+
render(<ComponentUnderTest as="form" ref={ref} />)
28+
expect(ref.current).toBeInstanceOf(HTMLFormElement)
29+
})
30+
})

0 commit comments

Comments
 (0)