Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to use ref in ReactJS

Getting Started with Ref in ReactJS

Ref is a term short for 'reference' in ReactJS. It is used to refer to an element or component returned by render(). It can be useful when you need direct access to the DOM element or an instance of a component.

Now, imagine refs as a way to label a specific element in your code, like marking your favorite book in a library. You can easily find it later when needed. That's what refs do in ReactJS, they help us point out an element or component for future reference.

Creating Refs

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 or component.

Let's look at an example:

class MyComponent extends React.Component {
  myRef = React.createRef();

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

In this code, myRef is created in a class component MyComponent. The myRef is then attached to a div using the ref attribute.

Accessing Refs

Once a ref is attached to an element, the ref can be used to access that element. The value of the ref can be accessed directly with .current.

Here's how to do it:

class MyComponent extends React.Component {
  myRef = React.createRef();

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

  componentDidMount() {
    console.log(this.myRef.current);
  }
}

In this example, console.log(this.myRef.current) is used to log the reference to the console. This will be executed after the component mount, thanks to componentDidMount() lifecycle method.

When to use Refs

Refs are handy for managing focus, text selection, triggering imperative animations, or integrating with third-party DOM libraries. But remember, use them sparingly. If you find yourself often using refs to "make things happen" in your app, it might be worth it to take a step back and consider a more idiomatic way to manage state in your application.

Here's an example of using refs to manage focus:

class CustomTextInput extends React.Component {
  textInput = React.createRef();

  focusTextInput = () => {
    // Directly using the DOM API
    this.textInput.current.focus();
  };

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput} />
        <button onClick={this.focusTextInput}>Focus the text input</button>
      </div>
    );
  }
}

In this example, the input field is automatically focused when the button is clicked, all thanks to the power of refs.

Refs with Function Components

As a rule of thumb, you cannot use refs in functional components because they don’t have instances. But, you can use refs in functional components if you use hooks, specifically the useRef hook.

Here's how it works:

import React, { useRef } from 'react';

function MyFunctionalComponent() {
  const myRef = useRef(null);

  function focusTextInput() {
    // Simulate a click on the text input using the raw DOM API
    myRef.current.focus();
  }

  return (
    <div>
      <input type="text" ref={myRef} />
      <button onClick={focusTextInput}>Focus the text input</button>
    </div>
  );
}

In this example, useRef hook is used to create a ref in a functional component, and it works quite similar to its counterpart in class components.

Conclusion

Think of refs as a secret passage to your favorite book in a library. It’s there when you need it, but you should not overuse it. ReactJS provides us with plenty of tools to manage our application state properly, and refs are just one of them.

When used correctly, refs can simplify our code and make certain tasks more straightforward. Just remember, when you start using refs to solve every problem, that's a sign you might need to reconsider your approach.

In fact, the beauty of React lies in its declarative nature, which allows us to describe what we want to achieve, and it takes care of the rest. So, keep exploring and happy coding!