pistacchio
pistacchio

Reputation: 58953

Typescript and React: How to have typed refs?

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

Upvotes: 1

Views: 1636

Answers (1)

Bruno Grieder
Bruno Grieder

Reputation: 29884

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

Upvotes: 5

Related Questions