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