Ad

Typescript And React: How To Have Typed Refs?

- 1 answer

I'm using Typescript with react. If I have a reference, for example

<SomeComponent ref="example-ref"></SomeComponent>

I can access it the usual way with this.refs['example-ref'] and work from there. If I want it typed, I have to explicitly cast it:

var typedRef: SomeComponent = this.refs['example-ref'] as SomeComponent;

But how can I have typed references so that I don't have to cast them? Thanks

Ad

Answer

Using an alternative refsyntax works well for us i.e. declare a private var in the class

private comp: SomeComponent;

and then in the TSX

<SomeComponent ref={(c) => { this.comp = c } }/></SomeComponent>

Just access the typed this.comp in the rest of the code

Ad
source: stackoverflow.com
Ad