How to Create Refs in React.js?

In React, refs provide a way to reference a DOM element or a class component instance created by React. Refs are typically used when you need to access the underlying DOM nodes or React components directly.

Here's how you can create refs in React.

Creating Refs

You can create a ref by using the React.createRef() function. This creates a reference object that can be attached to a React element.

import React from 'react';

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

  render() {
    return <div ref={this.myRef}>Ref element</div>;
  }
}

In this example, this.myRef is created using React.createRef(), and it's attached to a <div> element using the ref attribute.

Accessing Refs

Once you have created a ref, you can access the underlying DOM node or React component instance using the .current property of the ref object.

const node = this.myRef.current;

You can access properties and methods of the referenced DOM node or component instance using this reference.

Using Refs

Refs are commonly used for:

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

Here's an example of using a ref to focus an input element.

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.myRef.current.focus();
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.myRef} />
        <button onClick={this.handleClick}>Focus Input</button>
      </div>
    );
  }
}

In this example, when the button is clicked, the handleClick method is called, which then focuses the input element using the ref.

Cleaning Up Refs

When a component unmounts, React automatically cleans up the references to the DOM nodes or component instances created using refs. You can also manually clean up a ref by setting it to null.

componentWillUnmount() {
  this.myRef.current = null;
}

This can be useful to prevent memory leaks when a component is unmounted.

That's a basic overview of how to create and use refs in React. They're powerful tools for accessing and manipulating the DOM directly within your React components.