Skip to content

Add immutable forwardRef typing alternative #323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 5, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/basic/getting-started/forward-create-ref.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,30 @@ export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
));
```

<details>
<summary>

Side note: the `ref` you get from `forwardRef` is mutable so you can assign to it if needed.

</summary>

This was done [on purpose](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43265/). You can make it immutable if you have to - assign `React.Ref` if you want to ensure nobody reassigns it:

```tsx
type Props = { children: React.ReactNode; type: "submit" | "button" };
export type Ref = HTMLButtonElement;
export const FancyButton = React.forwardRef(
(props: Props, ref: React.Ref<Ref>) => ( // <-- here!
<button ref={ref} className="MyClassName" type={props.type}>
{props.children}
</button>
)
);
```

</details>


If you are grabbing the props of a component that forwards refs, use [`ComponentPropsWithRef`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/a05cc538a42243c632f054e42eab483ebf1560ab/types/react/index.d.ts#L770).

More info: https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315
Expand Down