Adding Types To Refs In React Using TypeScript – How To Do It?

Adding Types to Refs in React using TypeScript

If you are learning to use TypeScript combined with ReactJS, it will be a bit confusing when adding types to Refs in React using TypeScript. So let’s move on to our detailed tutorial to make it more straightforward.

How to adding Types to Refs in React using TypeScript

If you don’t know, the most crucial thing about TypeScript is contributing syntax of types. All the type in TypeScript is : ( Number, String, Enum, Boolean, Any, Void, Never, Array, Object, Type assertions, Null and Undefined, and Tuple ). All of that types make TypeScript logic become Strictly and make easier to maintain.

To add types to the useRef React, you will need to add a generic it looks like this '<T>.' There are a whole bunch of types for useRef, and you have to discover them by yourself. But in this tutorial, I will show you some common types.

Method 1: Example in Class Components with HTMLDivElement type 

let RefDiv = createRef<HTMLDivElement>();

The code above will set this—RefDiv to a RefObject that takes a ref type HTMLDivElement without any parameters.

In the render method, we will use RefDiv like ordinary:

componentDidMount(){
    if ( this.RefDiv){
      console.log(`callbackRef div width : ${this.refDiv.clientWidth}`)
    }
  }

Method 2: Example with Function Component with HTMLInputElement 

  import { createRef, useEffect, useRef } from "react";
 
 const Ref= ()=>{
  const RefInput = useRef<HTMLInputElement>();
  useEffect(()=>{
    RefInput?.current?.focus();},[]
  )
  return (
  <>
  <input type="text" ref={RefInput}/>
  </>)}
export default Ref;

If you want to access a DOM element inside a child React component from within the parent, you can use forwarding refs.

Method 3: Example with Forwarding Refs 

import { Component, createRef, forwardRef, useEffect, useRef } from "react";
 
 const Ref= ()=>{
 const Forward = forwardRef((props,ref:Ref<HTMLDivElement>)=>
 (<div ref = {ref} style={{width:'100%' , backgroundColor :'green'}}></div>)
 )
 function ForwardRef(){
  const Refdiv = useRef<HTMLDivElement>(null);
  useEffect(()=>{
    if(Refdiv.current){
      console.log(`forwardRef div width: ${Refdiv.current.clientWidth}`);
    }
  })
  return <ForwardRef ref={Refdiv}></ForwardRef>
}
export default Ref;

Summary

In this tutorial, I showed and explained some examples of adding type to refs in React using TypeScript. You can use generic with type to specific type of useRef() hook.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *