2

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

2
  • in order to use getData outside that component, you need to pass it as prop Commented Mar 6, 2020 at 21:32
  • Where is your ref? Do you mean ref as the react concept, or as the general concept of reference? Commented Mar 8, 2020 at 22:25

1 Answer 1

4
+100

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()
}
Sign up to request clarification or add additional context in comments.

4 Comments

I've created a code sandbox: codesandbox.io/s/…
Thank you, however it really doesnt let me to use SomeComponent as a type. Check my edit. Whats going on?
Odd, could you share a repro on code sandbox? Maybe try createRef<typeof SomeComponent>, although it shouldn't be necessary in this case.
Ok Anthony, the problem was the SomeComponent was connected with redux and the ref was forwared. However I decided to disconnect that component from store and it seems to work properly now. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.