Akshar Patel Akshar Patel - 1 year ago 362
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) {
this.state = {
count: 0

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download