createRef in React by Diwakar Kashyap

DiwakarDiwakar
2 min read

In React, createRef is a method used to access the DOM nodes or React elements created in the render method. Refs provide a way to interact with the underlying DOM elements, and they can be useful in various scenarios, such as managing focus, triggering animations, or integrating third-party libraries.

Here's a step-by-step guide on how to use createRef in React:

  1. Initialization:
    Create a ref instance using createRef and assign it to a class property.

     class MyComponent extends React.Component {
         constructor(props) {
             super(props);
             this.myRef = React.createRef();
         }
    
  2. Attaching to Elements:
    Attach the ref instance to a React element using the ref prop.

     render() {
         return <div ref={this.myRef}>Hello, World!</div>;
     }
    
  3. Accessing the Ref:
    Once you've attached the ref to an element, you can access that element directly through this.myRef.current.

     componentDidMount() {
         console.log(this.myRef.current);  // This will log the <div> element to the console
     }
    
  4. Usage Scenarios:
    Refs are useful in various scenarios:

  • Managing focus: Focus on an input element when a component mounts.

  • Triggering animations: By accessing the DOM element, you can use libraries like GSAP to trigger animations.

  • Integrating third-party libraries: Sometimes, you need to integrate third-party libraries that require direct access to the DOM. Refs can help here.

  1. Important Points:
  • Avoid using refs for things that can be done declaratively. For example, instead of using refs to "set" a property on a child component, use props.

  • Refs do not trigger a re-render when their content changes. They're just a way to access the DOM or React elements.

  • While you can assign a ref to a functional component, it needs to use forwardRef to pass the ref along to a DOM element.

Remember that while refs are powerful, they should be used sparingly. In many cases, you can achieve the desired behavior more declaratively using React's usual data flow mechanisms.

Thank you for reading. I encourage you to follow me on Twitter where I regularly share content about JavaScript and React, as well as contribute to open-source projects. I am currently seeking a remote job or internship.

Twitter: https://twitter.com/Diwakar_766

GitHub: https://github.com/DIWAKARKASHYAP

Portfolio: https://diwakar-portfolio.vercel.app/

0
Subscribe to my newsletter

Read articles from Diwakar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Diwakar
Diwakar

As a passionate developer, I thrive on acquiring new knowledge. My journey began with web development, and I am now actively engaged in open source contributions, aiding individuals and businesses.