Add TypeScript To An Existing React Project
Learn how to add TypeScript to your existing React project in a few simple steps.
Using useRef
with native elements can be a bit of a pain. You need to specify the type of the element you're targeting, but it's not always clear what type you should be using.
tsx
import {useRef } from "react";constComponent = () => {// What goes here?constaudioRef =useRef <NoIdeaWhatGoesHere >(null);return <audio ref ={audioRef }>Hello</audio >;};
A simple solution is to hover over the type of ref
to check what it accepts:
tsx
import {useRef } from "react";constComponent = () => {// What goes here?constaudioRef =useRef <HTMLAudioElement >(null);return <audio ref ={audioRef }>Hello</audio >;};
But there's an easier way.
ElementRef
?You can use ElementRef
, a type helper from React, to easily extract the type from the element you're targeting.
tsx
import {useRef ,ElementRef } from "react";constComponent = () => {constaudioRef =useRef <ElementRef <"audio">>(null);return <audio ref ={audioRef }>Hello</audio >;};
This even works with custom components that use forwardRef
. You can use typeof
to pass them to ElementRef
, and it'll extract the type of the element that the component is forwarding to.
tsx
import {OtherComponent } from "./other-component";importReact , {useRef ,ElementRef } from "react";// Pass it in via typeof!typeOtherComponentRef =ElementRef <typeofOtherComponent >;constComponent = () => {constref =useRef <OtherComponentRef >(null);return <OtherComponent ref ={ref }>Hello</OtherComponent >;};
If you're using the previous solution (with HTMLAudioElement
or HTMLDivElement
, etc.), there's no reason to change it. But if you're ever unsure what type to use, ElementRef
is a great helper.
And if you want more tips like this, check out my free React and TypeScript beginner's course. There are 21 interactive exercises packed with TypeScript tips and tricks for React apps.
Share this article with your friends
Learn how to add TypeScript to your existing React project in a few simple steps.
Learn the essential TypeScript configuration options and create a concise tsconfig.json file for your projects with this helpful cheatsheet.
Big projects like Svelte and Drizzle are not abandoning TypeScript, despite some recent claims.
Learn different ways to pass a component as a prop in React: passing JSX, using React.ComponentType, and using React.ElementType.
Learn about TypeScript performance and how it affects code type-checking speed, autocomplete, and build times in your editor.
When typing React props in a TypeScript app, using interfaces is recommended, especially when dealing with complex intersections of props.