Created
April 19, 2023 07:46
-
-
Save adrianbrowning/c99f5b300043bb28db5e11d9228ac334 to your computer and use it in GitHub Desktop.
react-forwardref.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://fettblog.eu/typescript-react-generic-forward-refs/ | |
| declare module "react" { | |
| function forwardRef<T, P = {}>( | |
| render: (props: P, ref: React.Ref<T>) => React.ReactElement | null | |
| ): (props: P & React.RefAttributes<T>) => React.ReactElement | null; | |
| } | |
| // Usage | |
| // Just write your components like you're used to! | |
| type ClickableListProps<T> = { | |
| items: T[]; | |
| onSelect: (item: T) => void; | |
| }; | |
| function ClickableListInner<T>( | |
| props: ClickableListProps<T>, | |
| ref: React.ForwardedRef<HTMLUListElement> | |
| ) { | |
| return ( | |
| <ul ref={ref}> | |
| {props.items.map((item, i) => ( | |
| <li key={i}> | |
| <button onClick={(el) => props.onSelect(item)}>Select</button> | |
| {item} | |
| </li> | |
| ))} | |
| </ul> | |
| ); | |
| } | |
| export const ClickableList = React.forwardRef(ClickableListInner); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment