Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to use TypeScript with React?
Next article icon

How To Use refs in React With TypeScript?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using refs Inside the class-based component with TypeScript
  • Using refs inside the functional components 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 TypeScript

Approach 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 TypeScript

Difference 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.


Next Article
How to use TypeScript with React?

A

abhish8rzd
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS
  • TypeScript

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. Prere
    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
  • How to use jQuery with TypeScript ?
    In this article, we will learn how we can use jQuery with TypeScript and implement the features of both languages. The below approach can be used to implement jQuery in TypeScript. By installing jQuery using the npm commandThe jQuery can be installed in your current TypeScript project folder using t
    2 min read
  • How To Use React Context In NextJS With Typescript?
    React introduced Context to simply managing global consistent states in application. In this article we will how to use React Context for consistent states across various components with Next.js, the most popular and widely used React meta framework, and with TypeScript or complete type safety. Prer
    4 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
  • How to use styles in ReactJS ?
    React is a popular JavaScript library for building single-page applications (SPAs) with dynamic user interfaces. Styling in React can be done in various ways, each with its advantages. In this article, we will explore different approaches to applying styles in React, including inline styles, CSS fil
    4 min read
  • How to use Context API with TypeScript and Next.js?
    The Context API in React provides a way to pass data through the component tree without having to pass props down manually at every level. When working with TypeScript and Next.js, leveraging the Context API allows for a more organized and type-safe approach to managing the global state. In this tut
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences