forwardRef/createRef

Check the Hooks section for useRef.

createRef:

class CssThemeProvider extends React.PureComponent<Props> {
private rootRef = React.createRef<HTMLDivElement>(); // like this
render() {
return <div ref={this.rootRef}>{this.props.children}</div>;
}
}

forwardRef:

type Props = { children: React.ReactNode; type: "submit" | "button" };
export type Ref = HTMLButtonElement;
export const FancyButton = React.forwardRef<Ref, Props>((props, ref) => (
<button ref={ref} className="MyClassName" type={props.type}>
{props.children}
</button>
));
Side note: the `ref` you get from `forwardRef` is mutable so you can assign to it if needed.

This was done on purpose. You can make it immutable if you have to - assign React.Ref if you want to ensure nobody reassigns it:

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>
));

If you are grabbing the props of a component that forwards refs, use ComponentPropsWithRef.

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

You may also wish to do Conditional Rendering with forwardRef.

Something to add? File an issue.