ReactJS – Refs

Refs in React provide a way to access and interact with DOM nodes or React elements created in the render method. They are useful for situations where you need to directly manipulate the DOM, such as focusing an input, managing scroll positions, or integrating with third-party libraries that require direct DOM manipulation.

Creating Refs

Refs are created using React.createRef() and are attached to React elements via the ref attribute. Once a ref is created, it can be used to access the corresponding DOM element.

Basic Example of Using Refs

Let’s create a simple example where we use refs to focus an input field when a button is clicked.

Step 1: Create a New React Application

First, create a new React application if you don’t have one already.

npx create-react-app my-app
cd my-app
npm start

Step 2: Create a Component that Uses Refs

Create a new file FocusInput.js and add the following code:

import React, { Component } from 'react';

class FocusInput extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  componentDidMount() {
    // Focus the input element when the component mounts
    this.inputRef.current.focus();
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} />
      </div>
    );
  }
}

export default FocusInput;

Explanation:

  1. Creating a Ref:
    • The inputRef is created using React.createRef() in the constructor.
  2. Attaching the Ref:
    • The inputRef is attached to the input element using the ref attribute.
  3. Accessing the Ref:
    • In the componentDidMount lifecycle method, this.inputRef.current gives access to the DOM node, allowing the input element to be focused.

Step 3: Use the Component

Modify the App.js file to include the FocusInput component:

import React from 'react';
import './App.css';
import FocusInput from './FocusInput';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>React Refs Example</h1>
        <FocusInput />
      </header>
    </div>
  );
}

export default App;

Using Refs in Functional Components

Refs can also be used in functional components with the useRef hook. Here’s an example:

Create a new file FocusInputFunctional.js and add the following code:

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

function FocusInputFunctional() {
  const inputRef = useRef(null);

  useEffect(() => {
    // Focus the input element when the component mounts
    inputRef.current.focus();
  }, []);

  return (
    <div>
      <input type="text" ref={inputRef} />
    </div>
  );
}

export default FocusInputFunctional;

Explanation:

  1. Creating a Ref:
    • The inputRef is created using the useRef hook.
  2. Attaching the Ref:
    • The inputRef is attached to the input element using the ref attribute.
  3. Accessing the Ref:
    • In the useEffect hook, inputRef.current gives access to the DOM node, allowing the input element to be focused. The empty dependency array [] ensures this effect runs only once, after the initial render.

Summary

  • Creating Refs: Use React.createRef() in class components or the useRef hook in functional components.
  • Attaching Refs: Attach the ref to a React element via the ref attribute.
  • Accessing Refs: Access the DOM node using ref.current.

Refs provide a way to directly interact with the DOM in React applications, useful for managing focus, text selection, or triggering animations. They should be used sparingly and only when absolutely necessary to interact with the DOM.


Tutorials Deck

TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

Languages

Web Technologies

Database

Trending Technologies

© 2024. All rights reserved.

Contact Us @ tutorialsdeck06@gmail.com