How to use refs in React with TypeScript ?

We will explore how to use React refs with TypeScript. In React, refs provide a way to access DOM elements directly without React’s involvement. This allows us to both retrieve and modify the values of DOM elements, similar to how we would in pure JavaScript.

When using React with TypeScript, we can write cleaner and more accurate code. However, there are some considerations to keep in mind. We need to save files with the “.tsx” extension and explicitly type the refs at the time of their declaration, as we cannot define refs directly in React when using TypeScript.

We will see the use of the React refs with TypeScript inside the Class-Based Components and Functional Components with the help of practical implementation using the code examples.

Table of Content

  • Using refs Inside the class-based component with TypeScript
  • Using refs inside the functional components with TypeScript

Using refs Inside the class-based component with TypeScript

In the class-based components, the React refs will be created using the React.createRef() method. But, we will use this method with an explicit type to specify the type of the ref using the <refType>.

Syntax:

private ref_name = React.createRef<refType>();

Example: The below code example will explain how you can create typed refs in React using TypeScript.

Javascript
import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends Component {
private inputRef = React.createRef<HTMLInputElement>();
private divRef = React.createRef<HTMLDivElement>();
formSubmitHandler = (e) => {
    e.preventDefault();
    if(inputRef.current.value){
    divRef.current.textContent = 
        "The entered value accessed using typed refs is: " + 
            inputRef.current.value;
    }
    else{
        divRef.current.textContent = 
            "Input field can not be Empty!!";
    }
};
render() {
    return (
    <div style={{textAlign: 'center'}}>
        <h1 style={{color: 'green'}}>w3wiki</h1>
        <form onSubmit={this.formSubmitHandler}>
        <input type="text" ref={this.inputRef} style={
        {
            padding: '8px', 
            borderRadius: '5px'
        }} />
        <br />
        <br />
        <button style={
        {
            color: '#fff', 
            background: 'green', 
            border: 'none', 
            padding: '10px', 
            cursor: 'pointer', 
            borderRadius: '5px'
            }}>
                Get Entered Value
            </button>
        </form>
        <div style={{marginTop: '30px'}} 
            ref={this.divRef}></div>
    </div>
    );
}
}

render(<App />, document.getElementById('root'));

Output:

Using refs inside the functional components with TypeScript

The refs will be added using the useRef() hook when working with the functional components. We will use the same syntax <refType> to explicitly type the refs with a null value passed inside the parenthesis as parameter to set the initial value.

Syntax:

const refName = React.useRef<refType>(null);

Example: The below code example will explain how you can use the React refs with TypeScript inside the functional components.

Javascript
import React, { useRef } from 'react';
import { render } from 'react-dom';

// Functional Component
const App = () => {
    const inputRef = React.useRef < HTMLInputElement > (null);
    const divRef = React.useRef < HTMLDivElement > (null);

    // Handling Form Submission
    const formSubmitHandler = (e) => {
        e.preventDefault();
        if (inputRef.current.value) {
            divRef.current.textContent =
                "The entered value accessed using typed refs is: " +
                inputRef.current.value;
        }
        else {
            divRef.current.textContent = 
                "Input field can not be Empty!!";
        }
    };

    return (
        <div style={{ textAlign: 'center' }}>
            <h1 style={{ color: 'green' }}>w3wiki</h1>
            <form onSubmit={formSubmitHandler}>
                <input type="text" ref={inputRef} style={
                    {
                        padding: '8px',
                        borderRadius: '5px'
                    }
                } />
                <br />
                <br />
                <button style={
                    {
                        color: '#fff',
                        background: 'green',
                        border: 'none',
                        padding: '10px',
                        cursor: 'pointer',
                        borderRadius: '5px'
                    }}>
                    Get Entered Value
                </button>
            </form>
            <div style={{ marginTop: '30px' }} ref={divRef}></div>
        </div>
    );
}

Output:





Contact Us