ReactJS ForwardRef: An In-Depth Look

Read Time: 6 min
Read Time 6 min

Welcome to the thrilling world of ReactJS! If you’re a developer seeking to create dynamic, efficient, and high-performing user interfaces, you’re in the right place. In this blog, we’ll embark on a journey to explore the power of ReactJS forwardRef, a tool that’s as intriguing as it sounds! Before we delve into the depths of forwardRef react, let’s kick things off with a brief overview of ReactJS and its core concepts.

ReactJS is a JavaScript library that’s widely loved by developers worldwide. It was developed and maintained by Facebook, and it’s known for its prowess in creating interactive and complex User Interfaces (UIs).

ReactJS leverages a component-based architecture, a method that’s become a game-changer in the world of web development. This approach means we can create reusable UI components, significantly reducing code redundancy and making our code more readable and maintainable.

But ReactJS isn’t just about creating components. It’s also about how these components interact and communicate with each other. And that’s where concepts like ‘state’, ‘props’, and ‘refs’ come in. In the upcoming sections, we’ll be exploring refs, forwardRef, and the react createRef method, focusing on how these tools enable us to manage and control our components efficiently. So, buckle up and get ready for an exciting deep dive into the world of ReactJS forwardRef

Table Of Contents

What is ‘Refs’ in React?

Before we can delve into the concept of react forward ref, it’s crucial to grasp the fundamentals of refs themselves. Refs in ReactJS are a powerful tool for accessing and manipulating the DOM (Document Object Model) nodes in your application. They allow you to grab a reference to a specific element and make changes to it directly, bypassing the need for state or props. This can lead to improved performance and a smoother user experience.

How do refs work in React?

Refs are created using React.createRef() method or the useRef() hook in functional components. Once created, they can be attached to any JSX element by using the ref attribute. This creates a reference to the DOM node, which can then be accessed and manipulated directly.

For example, let’s say we have a button in our component that we want to focus on when the component mounts:

class MyComponent extends React.Component {

  constructor(props) {

    super(props);

    this.myRef = React.createRef();

  }

  componentDidMount() {

    this.myRef.current.focus();

  }

  render() {

    return <button ref={this.myRef}>Click me!</button>;

  }

}

In this example, we create a ref using React.createRef() and attach it to the button using the ref attribute. In the componentDidMount() method, we call the focus() method on the ref to give the button focus when the component mounts.

When to Use Refs in React?

Refs are your secret weapon when you need to directly interact with DOM elements or component instances. Here are some scenarios where you might need to use refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Working with Refs in Class Components 

In class components, refs are created using React.createRef() and attached to React elements via the ref attribute. Once a ref is attached to an element, the ref can be used to access the element’s properties. Here’s an example:

class MyComponent extends React.Component {

  myRef = React.createRef();

  componentDidMount() {

    this.myRef.current.focus();

  }

  render() {

    return <input ref={this.myRef} />;

  }

}

In this example, we create a ref using React.createRef() and assign it to the myRef property of the class instance. Then, we attach the ref to the input element. Finally, when the component mounts, we use the ref to focus on the input element.

Using Refs with Function Components 

In function components, refs are created using the useRef hook. Similar to class components, refs can be attached to React elements via the ref attribute. Here’s an example of using refs in a function component:

import React, { useRef, useEffect } from 'react';

function MyComponent() {

  const myRef = useRef();

  useEffect(() => {

    myRef.current.focus();

  }, []);

  return <input ref={myRef} />;

}

In this example, we create a ref using the useRef hook and attach it to the input element. Then, we use the useEffect hook to focus on the input element when the component mounts.

When Not to Use Refs in React 

While refs can be incredibly useful, they should be used sparingly and only in specific scenarios. Refs essentially bypass the standard React data flow, making your code less predictable and harder to debug. Here are some instances where you should avoid using refs:

  1. State Management: Do not use refs to manage the state of a component. Instead, use the useState hook in function components or setState in class components.
  2. Triggering Re-renders: Refs don’t trigger re-renders when their values change. If you need to trigger a re-render, consider using state instead.
  3. Parent-Child Communication: Avoid using refs for parent-child communication. Instead, rely on the standard method of passing props.

Defining ForwardRef in ReactJS

ForwardRef is a higher-order function in ReactJS that allows a parent component to pass a ref directly to a child component. This capability is especially useful when you want to access a child component’s DOM node or instance from a parent component.

In other words, forwardRef enables us to “forward” a ref from a parent component to its child component, allowing for more control and flexibility when working with refs.

How ForwardRef Differs from Normal Refs

While both normal refs and forwardRef provide access to DOM nodes or component instances, there is a key difference between them. Normal refs are used to create a ref within a component, allowing that component to access its own DOM nodes or instances.

On the other hand, reactjs forwardRef is used when you want a parent component to access a child component’s DOM node or instance directly. It’s like creating a direct line of communication between the parent and the child component, bypassing the typical React data flow that relies on state and props.

Different Scenarios to Use forwardRef() in React?

ReactJS ForwardRef is particularly useful in the following situations:

1. Accessing a child component’s DOM node

Sometimes, you need to interact with a child component’s DOM node from the parent component. For example, you may want to set focus on an input field within a child component when a button in the parent component is clicked.

2. Creating reusable and flexible components

When creating a library of components, ReactJS forwardRef can be valuable in providing more flexibility to users of your components. By forwarding refs, you allow users to access and manipulate the DOM nodes or instances of the child components directly, if needed.

3. Integration with third-party libraries

If you’re working with third-party libraries that rely on direct DOM manipulation, forwardRef can help you create seamless integration between React components and the library.

Different Examples of Using ForwardRef

With the theory of ReactJS forwardRef under our belts, it’s time to roll up our sleeves and get our hands dirty with some real-world examples. Let’s explore how forwardRef can be used in a ReactJS application, and even how it can be used with TypeScript!

A Simple Example of Using ForwardRef in ReactJS

Let’s start with a basic application of ReactJS forwardRef. Consider a parent component that needs to control the focus of an input element in a child component. Here’s how you could achieve this with forwardRef:

import React, { forwardRef } from 'react';

const CustomInput = forwardRef((props, ref) => (

  <input ref={ref} className="custom-input" {...props} />

));

class ParentComponent extends React.Component {

  inputRef = React.createRef();

  focusInput = () => {

    this.inputRef.current.focus();

  };

  render() {

    return (

      <div>

        <CustomInput ref={this.inputRef} />

        <button onClick={this.focusInput}>Focus the input</button>

      </div>

    );

  }

}

export default ParentComponent;

In this example, the CustomInput component forwards its ref to the input element. The ParentComponent then attaches inputRef to the CustomInput, allowing it to directly access and focus the input element when the button is clicked.

Using ForwardRef with TypeScript

When it comes to using forwardRef with TypeScript, you need to define the type of the ref being forwarded. Let’s modify our previous example to use react forwardref typescript:

import React, { forwardRef, Ref, ForwardRefRenderFunction } from 'react';

interface CustomInputProps {

  placeholder?: string;

}

const CustomInput: ForwardRefRenderFunction<HTMLInputElement, CustomInputProps> = 

  (props, ref) => (

  <input ref={ref} className="custom-input" {...props} />

);

export default forwardRef<HTMLInputElement, CustomInputProps>(CustomInput);

In this example, we first define an interface CustomInputProps to type-check the props of our CustomInput

Conclusion

As our deep dive into forwardRef in ReactJS comes to an end, let’s take a moment to reflect on the treasures we’ve uncovered along the way.

ForwardRef is a higher-order function in ReactJS that allows us to “forward” a ref from a parent component to its child component. This capability provides us with more control and flexibility when dealing with refs, enabling us to directly access and manipulate a child component’s DOM node or instance from the parent component.

We also discovered how react forwarding refs stands out from traditional refs. While normal refs allow a component to access its own DOM nodes or instances, forwardRef takes it a step further by enabling a parent component to directly access a child component’s DOM node or instance. This unique feature is particularly beneficial in scenarios such as accessing a child component’s DOM node, creating reusable and flexible components, and integrating with third-party libraries.

If you encounter any issues or need further assistance with your React application, don’t hesitate to contact APPWRK. Our expert team of ReactJS developers is always ready to provide reliable and efficient support for all your React needs. Whether you’re facing issues with performance, scalability, or any other aspect of your React application, our team has the skills and expertise to help you overcome any challenges. So, if you want to ensure that your React application is running at its best, contact APPWRK today and experience the benefits of working with top-notch ReactJS developers.

About author

Gourav Khanna

Gourav Khanna is co-founder and CEO of APPWRK IT SOLUTIONS PVT LIMITED, a web & mobile app development company. He is a technophile who is always eager to learn and share his views on new technologies and future advancements. Gourav’s knowledge and experience have made him one of the industry's most respected and referenced leaders in the IT industry. His passion for writing and a high spirit of learning new things is reflected in his write ups. He has inspired many organizations to leverage digital platforms with his top-notch writing strategy skills that cut through the noise, backed by sharp thinking. Gourav believes that - “Words are the way to know ecstasy, without them life is barren ''.

Redesign, Rebuild and Reclaim with APPWRK.

Whether you are planning a start-up or want to enhance your existing business, APPWRK is a one-stop solution to satisfy your goals and expectations. We have action-oriented experience in UI/UX, Mobile, and Web App development. Also, you can knock on our door for Quality Assurance and Digital Marketing services.

Book A Consultation Now! Book a Consultation Now!
Related Post
Our Premium Clientele

and many more...

APPWRK Clients' Success Stories
Call Us whatsapp skype