Akshar Patel Akshar Patel - 25 days ago 31
TypeScript Question

How to use refs in react with Typescript

I'm using Typescript with React. I'm having trouble understanding how to use refs so as to get static typing and intellisense with respect to the react nodes referenced by the refs. My code is as follows.

import * as React from 'react';

interface AppState {
count: number;
}

interface AppProps {
steps: number;
}

interface AppRefs {
stepInput: HTMLInputElement;
}

export default class TestApp extends React.Component<AppProps, AppState> {

constructor(props: AppProps) {
super(props);
this.state = {
count: 0
};
}

incrementCounter() {
this.setState({count: this.state.count + 1});
}

render() {
return (
<div>
<h1>Hello World</h1>
<input type="text" ref="stepInput" />
<button onClick={() => this.incrementCounter()}>Increment</button>
Count : {this.state.count}
</div>
);
}}

Answer

Found the answer to the problem. Use refs as below inside the class.

refs: {
    [key: string]: (Element);
    stepInput: (HTMLInputElement);
}

Thanks @basarat for pointing in the right direction.

Comments