Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.createRef current type in typescript

I'm trying to find what to type React.createRef as. Header is a custom component. header.current always says

(property) React.RefObject.current: unknown Object is of type 'unknown'.

I can set it to type <any> but that's the easy way out. How do I get Typescript to play nice and stop complaining.

Example: React.createRef<any>()

Fully code:

   const header = React.createRef();
    const { container } = render(
      <Header{...props} headerRef={header} />,
    );
    const el = header.current.getButtonElement("button");

I've even tried setting it to a HTMLDivElement which is what it returns.

const header = React.createRef<HTMLDivElement>();

but the below still gives me an error: (property) React.RefObject.current: HTMLDivElement | null Object is possibly 'null'.

const el = header.current.getButtonElement("button");
like image 259
me-me Avatar asked Oct 22 '25 07:10

me-me


1 Answers

This makes sense. TypeScript is trying to warn you that calling getButtonElement on something that MIGHT be undefined is "dangerous". You can work around this by refining the type first, like this:

const header = React.createRef<HTMLDivElement>();

// In test
const currentHeader = header.current;
if (!currentHeader) {
    // Handle the case where header isn't set yet
}

currentHeader.getButtonElement("button"); // At this point TypeScript knows currentHeader can't be null so the type check passes
like image 172
Milton Avatar answered Oct 23 '25 22:10

Milton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!