Type React component with ref? Typescript

Viewed 229

So I have a ref:

someComponent;

And the someComponent is basically a React component that looks like:

class SomeComponent<IProps> {
   getData = () => {};

   render() {
      ...some stuff
   }
}

So, how can I type someComponent so if I do:

this.someComponent.getData();

The TypeScript won't shout that getData doesn't exist on this.someComponent?

I tried:

someComponent: React.RefObject<SomeComponent<IProps>>

But TypeScript still warns me.

Edit: Tried with createRef, however getting following error: enter image description here

1 Answers

You need to specify the type of the component when you declare the ref in the parent component:

someComponent = React.createRef<SomeComponent>();

And pass the ref to the rendered component:

<SomeComponent ref={this.someComponent} />

Then you can call getData like this:

if (this.someComponent.current !== null) {
  this.someComponent.current.getData()
}
Related