Refs in React provide access to DOM elements of a web page. Typescript has type inference and Refs added to TSX, So we have to declare refs of a type HTMLInputElement or any DOM API type.

React Typescript refs example

This example explains adding focus to the input box in the react component. In Javascript, We used createRef() which is a Generic function of any type.

   inputRef = React.createRef();

In Typescript, Declare ref’s of type using Generic Syntax.

  inputRef = React.createRef<HTMLInputElement>();

Adding the created inputRef to the input element using the refs attribute

                     <input type="text" ref={this.inputRef} />

Access the refs using this.inputRef.current and focus using the focus() method.

        this.inputRef.current?.focus()

Here is a complete example

import React, { Component } from 'react';
//props object
type AppProps={
    counter:number;
}
//state object
type AppState={
    message:string;
}

class First extends Component {
    inputRef = React.createRef<HTMLInputElement>();

    componentDidMount(){
        this.inputRef.current?.focus()
    }

    render() {
        return (
            <div>
                     <input type="text" ref={this.inputRef} />
            </div>
        );
    }
}

export default First;

Here is a Functional component createRef example.

import React, { createRef } from 'react';

interface MessageProps{}


function Second(props:MessageProps){
    const inputRef = createRef<HTMLInputElement>();

    return (
        <div>
                     <input type="text" ref={inputRef} />
            </div>
    );
};

export default Second;