Page Content

Tutorials

What Are References Component in React.js With Example

References Component in React.js

Refs, short for references, give React.js users access to DOM nodes or React elements that were produced using the render method. Although the majority of UI modifications are frequently handled automatically by React’s declarative approach, there are still situations in which direct contact with the underlying DOM elements or instances of components is required; in these cases, Refs are quite helpful. Focus management, text selection that happens automatically, media playback control, scroll position setting, and form handling in “uncontrolled components” are some examples of these situations.

This.refs.myInput can be used to access a ref that has been created for class components using the ref attribute (e.g., ). In functional elements, the applicationA value or DOM node that is not directly involved in rendering can be persistently referenced using the Ref Hook, and its current value can be accessed via the.current property. It is crucial to keep in mind that a ref object acquired using this.refs is a React-wrapped object, and in order to extract the real DOM node it references Component, the getDOMNode() method is required.

References Component
References Component

Purpose and Use Cases of Refs

When interacting with a DOM element or component instance that challenges props and state, references Component are used more. React components take care of their own state and props, so data goes one way. But occasionally, a direct “handle” to a rendered element is necessary.

Typical Refs use cases include:

Managing focus, text selection, or media playback: React’s “refs” feature lets components directly interact with DOM elements to manage attention, text selection, and media playback. Refs provide a handle to a DOM node or class component instance. React prefers declarative DOM updates, however references Component are needed in some cases.

Triggering imperative animations: Instead of using React’s declarative rendering cycle, imperative animations in React are triggered by directly interacting with the Document Object Model (DOM) or time-based JavaScript methods. React prefers a declarative style where the UI states its end-state and React quickly updates the DOM, although developers can utilise refs to directly access a DOM node.

Integrating with third-party DOM libraries: Charting libraries and jQuery plugins require direct access to the DOM element. React apps employ a Virtual DOM to change the user interface without direct DOM manipulation. This improves performance because straight DOM operations are expensive.

Getting DOM measurements: React DOM measurements require specialised developer tools and capabilities to reveal how components affect the Document Object Model. In the Chrome and Firefox React Developer Tools browser plugin, the “Profiler” tab records interactions and measures component rendering times, generating flamegraphs to identify slow or process-intensive components.

Clearing input fields: React references Component can clear input fields in uncontrolled components. Uncontrolled components have no input value set by React, so the application must synchronise the component state and input value.

When to Use State/Props vs. References

Recognising that Refs should be used sparingly is essential. React’s data flow, which employs state to manage internal data and props to move data down, is suggested for component interaction and UI updates.Refs should not be used for declarative tasks. Instead of using a Ref to edit the content of a <p> tag, you might update the component’s state and use the render() function to re-render the new text. Refs are useful when performance-critical conditions require avoiding re-renders by directly manipulating the DOM or hastily changing a child outside React’s data flow.

To properly manage data and component behaviour in React while upholding the one-way data flow concept, it is essential to choose between state, props, and refs. The main purpose of props, which are short for properties, is to transfer data and methods from a parent component to a child component. Props are parameters supplied to a JSX element. They can be of different JavaScript data types, such as strings, numbers, functions, arrays, and even other React components, and serve as configuration options for a component during its initialisation. One basic rule is that props are immutable and read-only; the child component that receives them should never change them.

React takes care of swapping out the old props for new ones and re-rendering the component if a parent component modifies a prop’s value. React offers PropTypes and default to validate the types of incoming props.Fallback values for optional properties can be set using props. Child components can use function callbacks supplied as props to connect with their parents. Furthermore, component composition is made easier by the props.children special prop’s ability to send nested JSX elements.

How to Create and Access Refs

React refs allow direct access to DOM elements and components. As handles, they relate to component parts. React allows refs for class components.createRef() and attach it to an element with ref. This ref can be used to retrieve the underlying DOM node using getDOMNode() or findDOMNode from react-dom. For functional parts, utiliseThe ref hook is the official ref creation method. Refs are important for DOM measurements, component methods, and interactive behaviours like focus control, automated text selection, media playback control, and scroll position.

Depending on the React version and whether you’re dealing with class or functional components, there are multiple ways to build and use Refs:

Callback Refs (Older method, but still valid and flexible): An element or component’s ref attribute receives a function using this approach. The function receives null when unmounted and the genuine DOM element or component when mounted. This reference can be kept in a variable inside the closure of a functional component or in a class property.

React.createRef() (Class Components – Recommended): React.createRef(), introduced in React 16.3, is recommended for class component Refs. You give React a call.To build a Ref object, use the constructor’s createRef(). Next, you add this Ref object to a React element’s ref attribute. After the references component mounts, the actual DOM element or references component instance will be stored in the.current field of the Ref object.

useRef() Hook (Functional Components – Recommended): Functional components can use Refs with useRef(), which was introduced with React Hooks (React 16.8 and later). The specified argument (or undefined if none is supplied) is initialised in the.current property of the mutable ref object that is returned.

For the duration of the component’s existence, the returned object will remain in place. UseState modifications do not re-render, unlike the.current attribute. Because of this, useRef can hold non-rendering values or interact with the DOM directly without re-rendering.

Accessing the Underlying DOM Node

The current attribute of the Ref object will point directly to the DOM element itself when a Ref is associated to an HTML element (such as <input>, <div>, etc.). This enables you to work directly with its properties or execute native DOM functions on it, such focus() and scrollIntoView().

The instance of a custom React component will be stored in the current property if a Ref is attached to it (for example, <MyCustomComponent />). Only when the custom component is a class component is this feasible. Functional component references Component must be sent to DOM elements or class components using React.forwardRef.

ReactDOM returns a React component’s DOM node.Due to its imperative nature, findDOMNode() is usually not allowed for direct DOM manipulation without third-party frameworks. FindDOMNode is less important when using createRef or useRef because you can tie the ref to your references component’s DOM element in.current.

Code Example:

Let’s demonstrate a typical use case: when a references component loads, an input field is immediately focused; a button is then provided to clear and refocus the field. Since this is the most recent recommended method for state and side effects, we will employ useRef and useState in a functional component.

import React, { useRef, useEffect } from 'react';
function FocusInputWithRef() {
  
  const inputRef = useRef(null);
  useEffect(() => {
    inputRef.current.focus();
  }, []); 
  const handleClearAndFocus = () => {
    inputRef.current.value = '';
    inputRef.current.focus();
  };
  return (
    <div className="min-h-screen bg-gray-100 flex items-center justify-center p-4 font-inter antialiased">
      <script src="https://cdn.tailwindcss.com"></script>
      <div className="w-full max-w-sm p-6 bg-white rounded-xl shadow-lg space-y-4">
        <h2 className="text-2xl font-bold text-gray-800 text-center">Focus Input Demo</h2>
        <div className="space-y-2">
          <label htmlFor="ref-input" className="block text-sm font-medium text-gray-700">
            Click the button to clear and re-focus:
          </label>
          <input
            id="ref-input"
            type="text"
            ref={inputRef}
            placeholder="Type something here..."
            className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
        <button
          onClick={handleClearAndFocus}
          className="w-full bg-blue-500 text-white py-2 px-4 rounded-md font-semibold hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors"
        >
          Clear & Focus
        </button>
      </div>
    </div>
  );
}
export default FocusInputWithRef;

Output:

Focus Input Demo

Click the button to clear and re-focus:  Type something here...
Clear & Focus

Explanation of the Code Example

useRef(null):We use useRef(null) to initialise inputRef. This makes the current property of the changeable object null at first. After the references component renders, React will set inputRef.current to the real DOM input element.

value={inputValue} and onChange={handleChange}: The input field is a controlled element. The inputValue state variable controls its value, and the handleChange function updates inputValue in response to changes. This is how form inputs are handled in React by default.

ref={inputRef}:This is an important line. The inputRef object is affixed to the DOM element itself. This particular DOM element will now be referenced by inputRef.current.

useEffect(() => { … }, []): This Hook causes functional references components to have side effects.

  • Because of the [] empty dependency array, the function inside useEffect is run after the references component mounts.
  • This effect correctly uses the native DOM focus() function on the DOM element using inputRef.current. The input field activates when the page loaded.

handleClearAndFocus function:

  • setInputValue(”): To begin, we update the input field’s state to clear it. By doing this, the references component is rendered again with an empty input.
  • inputRef.current.focus(): Following clearing, we programmatically return focus to the input field using inputRef.current. It is acceptable to use Refs in this direct DOM interaction.

This example shows how Refs can be used to preserve state using normal React techniques (useState) while handling imperative DOM changes (like focus()) that are not directly handled by React’s declarative rendering process.

Conclusion

To sum up, React’s refs offer a strong but constrained tool for directly accessing and modifying DOM objects or references component instances outside of the standard state and prop driven React.js data flow. Even though React promotes declarative programming, refs are necessary for some critical use cases, like controlling focus, starting animations, integrating third-party libraries, and retrieving DOM measurements. Both class and functional components enable permanent references component across renders without requiring re-renders; class components usually utilise React.createRef() while functional components use the useRef() hook.

However, because misuse of references component can result in code that is more difficult to manage and debug, it is important to use them judiciously and refrain from depending on them for tasks that can be accomplished with state or props. In the end, developers may maintain the fundamental ideas of component-driven design and one-way data flow while bridging the gap between React’s virtual DOM and the real DOM as needed by learning how to use refs appropriately.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index