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:
-
Initialization:
Create a ref instance usingcreateRef
and assign it to a class property.
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); }
-
Attaching to Elements:
Attach the ref instance to a React element using theref
prop.
render() { return <div ref={this.myRef}>Hello, World!</div>; }
-
Accessing the Ref:
Once you've attached the ref to an element, you can access that element directly throughthis.myRef.current
.
componentDidMount() { console.log(this.myRef.current); // This will log the <div> element to the console }
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.
5.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/
Top comments (4)
Nice writeup, Why are you using class copmponent instead of functional?
In functional components, you cannot use createRef. Instead, you should use the useRef hook, which accomplishes the same task.
today i will write blog on useRef hook
Okay, I am seeing that class components are now replaced by functional and you're right useRef does the same for it.