Skip to content

Commit 064d10f

Browse files
authored
add forwardref
1 parent 18d261d commit 064d10f

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

README.md

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ Translations:
4242
* [Useful React Prop Type Examples](#useful-react-prop-type-examples)
4343
* [Forms and Events](#forms-and-events)
4444
* [Context](#context)
45-
* [Forwarding References/createRef](#forwarding-referencescreateref)
45+
* [forwardRef/createRef](#forwardrefcreateref)
4646
* [Portals](#portals)
4747
* [Error Boundaries](#error-boundaries)
4848
* [Concurrent React/React Suspense](#concurrent-reactreact-suspense)
@@ -535,19 +535,33 @@ const Consumer = Context.Consumer
535535

536536
[Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
537537

538-
## Forwarding References/createRef
538+
## forwardRef/createRef
539539

540-
Use a `React.RefObject`:
540+
`createRef`:
541541

542542
```tsx
543543
class CssThemeProvider extends React.PureComponent<Props> {
544-
private rootRef = React.createRef<HTMLDivElement>();
544+
private rootRef = React.createRef<HTMLDivElement>(); // like this
545545
render() {
546546
return <div ref={this.rootRef}>{this.props.children}</div>;
547547
}
548548
}
549549
```
550550

551+
`forwardRef`:
552+
553+
```tsx
554+
type Props = { children: React.ReactNode; type: 'submit | 'button' }
555+
export type Ref = HTMLButtonElement
556+
export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
557+
<button ref={ref} className="MyClassName" type={props.type}>
558+
{props.children}
559+
</button>
560+
))
561+
```
562+
563+
More info: https://medium.com/@martin_hotell/react-refs-with-typescript-a32d56c4d315
564+
551565
[Something to add? File an issue](https://github.com/sw-yx/react-typescript-cheatsheet/issues/new).
552566
553567
## Portals

0 commit comments

Comments
 (0)