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:
- Omit one optional parameter while providing another in TS
- Define types for process.env in TypeScript
- Extend an Interface excluding a Property in TypeScript

Hello, guys! I hope that my knowledge in HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, Python, MySQL, and npm computer languages may be of use to you. I’m Brent Johnson, a software developer.
Name of the university: HOU
Major: IT
Programming Languages: HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, PyThon, MySQL, npm