How To Use refs in React With TypeScript?
Last Updated :
14 Oct, 2024
To use refs in React with TypeScript, you can take advantage of the ref attribute to directly interact with DOM elements or child components. Refs provide a way to access the underlying DOM node or React component instance and can be especially useful when you need to manage focus, control animations, or store previous state values.
In this article, we’ll explore two main approaches for using refs in React with TypeScript:
Approach 1: Using refs Inside the class-based component with TypeScript
Class components are an older approach in React, but they are still widely used. In TypeScript, you can define refs in class components by creating a reference using React.createRef()
and attaching it to a DOM element.
Syntax:
private ref_name = React.createRef<refType>();
Example: The below code example will explain how you can create typed refs in React using TypeScript.
TypeScript
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' }}>GeeksforGeeks</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 class-based component with TypeScriptApproach 2: Using refs inside the functional components with TypeScript
With the introduction of hooks, functional components have become more common in modern React development. You can use the useRef hook in functional components to manage refs in TypeScript.
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.
TypeScript
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' }}>GeeksforGeeks</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:
Using refs inside the functional components with TypeScriptDifference Between Class Components and Functional Components with Refs
- In class components, refs are created using React.createRef() and accessed using this.inputRef.
- In functional components, refs are created using the useRef() hook, and you directly access the current value using inputRef.current.
Conclusion
To use refs in React with TypeScript, you can apply them in both class-based and functional components depending on the approach you're using. In class components, use React.createRef(), and in functional components, use useRef(). By specifying types like HTMLInputElement in TypeScript, you ensure type safety and can avoid potential runtime errors. This makes refs a powerful and efficient way to directly access DOM elements or component instances in your React application.
Similar Reads
How to use TypeScript with React? TypeScript enhances JavaScript by adding strict type definitions, making your code more robust and maintainable. ReactJS, a popular library for building user interfaces, pairs excellently with TypeScript to create clean, efficient, and scalable codebases. Combining TypeScript with React offers a pow
3 min read
How to redirect in React with Typescript ? Navigating users seamlessly through a React application is a fundamental aspect of creating a smooth and intuitive user experience. In this article, we delve into the world of redirects in React, specifically addressing the use of TypeScript for enhanced type safety and developer productivity.Prereq
2 min read
How to Use NextJS in Typescript? TypeScript enhances Next.js applications by adding static type checking and improves developer experience through type safety. Integrating TypeScript into your Next.js project helps catch errors early and improves code maintainability. It offers even greater productivity and robustness to your web d
5 min read
Should we use TypeScript with React Native ? React Native is used to creating apps for Both Android and iOS platforms. It allows you to use a single codebase for both platforms. One of the biggest advantages React Native provides is that it's easy to learn because you don't need to learn a whole new programming language for it. Because it uses
8 min read
How to Use TypeScript with Vite? Vite is a modern build tool known for its speed and efficiency. Using TypeScript with Vite combines Vite's fast development experience with TypeScript's strong static typing, enabling early error detection and more maintainable code. This integration enhances productivity and code quality in modern
3 min read
How to Get Value of Input in TypeScript ? In TypeScript, retrieving the value of an input element is a common task when building web applications. Whether you're handling form submissions, validating user input, or manipulating data based on user interactions, accessing input values is essential. The below approaches can be utilized to get
2 min read