Design Converter
Education
Last updated on Feb 20, 2025
•8 mins read
Last updated on Feb 20, 2025
•8 mins read
Need a way to access a DOM element in React?
React provides a handy tool for this—react createRef. This method lets you create a reference to an element, making it easy to interact with the DOM directly. Whether you're managing focus, handling animations, or storing values without triggering re-renders, refs can help.
This blog breaks down how to create and use refs in different React components. You'll see how refs work in class, function, and functional components. By the end, you'll know how to apply refs effectively in your projects.
The createref method is a built-in React function used to create refs in React. A ref, when attached to a react element, allows direct access to a dom element, making it possible to perform operations on an HTML dom element or trigger imperative animations on a dom element. Each ref attribute defined on a react component results in a ref object that receives the current property, which points to the associated dom element. Once the ref attribute created is assigned, the ref value becomes available via the current property of the ref object.
A mutable object produced by the createref method stores the ref and is often passed between child component and parent component. The ref attribute on a react element can be implemented through both callback refs and string refs. Callback refs call a function with the dom node as an argument, and string refs rely on a reference string that react manages internally. Both strategies enable direct manipulation of a dom node and support tasks such as managing focus and triggering imperative animations in user interfaces.
Refs in react also support integration with third party dom libraries, providing an escape hatch for scenarios where direct dom element manipulation is needed. Developers can pass refs from one react component to another, ensuring that each react component maintains a consistent connection to its underlying dom element. This approach is beneficial when the component instance must interact with an input element or any other dom element rendered in the render method.
In class components, ref attributes are typically managed in the constructor. A common pattern involves calling the createref method and storing the result in a ref object. The following code snippet demonstrates how to create refs in class components:
1import React from "react"; 2 3class MyComponent extends React.Component { 4 constructor(props) { 5 super(props); 6 this.myRef = React.createRef(); 7 } 8 componentDidMount() { 9 // Access the dom element through the current property 10 console log(this.myRef.current); 11 } 12 render() { 13 return <input element ref={this.myRef} />; 14 } 15} 16 17export default MyComponent;
This example uses the ref attribute to attach a reference to an input element, which is vital for managing focus and triggering imperative animations. The ref object receives the current property pointing to the dom node, and this pattern is commonly observed in class components. Such react component instances can then interact with the input element directly and work with third party dom libraries when needed. The ref attribute created here is part of a broader system in react where the createref method enables efficient communication with an HTML dom element.
Class components frequently require handling of the component's state while coordinating with the ref attribute. The pattern of calling create refs in a constructor ensures that the react component instance has a stable reference to the dom element throughout its lifecycle. As a result, operations on a dom node in a react component become more predictable, and managing focus on an input element or another dom element becomes straightforward.
Function components and functional components have also embraced the create a ref technique. In function mycomponent examples, a ref created via the createref method serves similar purposes as in class components. Although the useref hook is more common in only functional components, there are scenarios where the createref method remains relevant, especially when the current value is needed at render time.
Consider this function component implementation:
1import React from "react"; 2 3function MyComponent() { 4 const myRef = React.createRef(); 5 6 React.useEffect(() => { 7 // Managing focus on the input element using the current property 8 if (myRef.current) { 9 myRef.current.focus(); 10 } 11 console log(myRef.current); 12 }, []); 13 14 return <input element ref={myRef} />; 15} 16 17export default MyComponent;
In this snippet, both function components and functional components are illustrated. The ref attribute is applied to an input element to demonstrate managing focus and the reliance on the current property for accessing a dom element. Developers often pass refs between parent component and child component, ensuring that each react component maintains a clear reference to the underlying dom element. The example also shows the alternative of using callback refs, where a function is provided to assign the dom node directly. For instance, callback refs react can be implemented as follows:
1import React from "react"; 2 3function MyComponent() { 4 const setRef = node => { 5 // Save the dom node for further operations 6 if (node) { 7 console log("DOM node assigned:", node); 8 } 9 }; 10 11 return <input element ref={setRef} />; 12} 13 14export default MyComponent;
This callback refs approach demonstrates flexibility in assigning a dom element reference through a ref attribute. It ensures that the current property of the ref object holds the dom node, whether working with an input element or another dom element, and supports both parent component and child component interactions.
React refs serve multiple advanced use cases beyond simple element access. They are instrumental in managing focus and triggering imperative animations across various dom node instances. The current property on a ref object connects a react component instance directly to an HTML dom element, allowing developers to manage focus on an input element or perform animations that involve a dom element.
When an input field or any HTML element is rendered within a react component, the ref attribute ensures that the associated ref object receives the current property pointing to the actual dom node. This capability is highly beneficial for tasks such as managing focus and coordinating imperative animations, where precise control over a dom element is necessary. Developers can pass refs between react components so that both parent component and child component have access to the same dom node. This approach also supports integration with third party dom libraries that may require direct dom element manipulation.
Additionally, the use of callback refs and string refs provides multiple avenues for handling ref attributes in a react component. For example, callback refs react enable immediate assignment of a dom element during the render method, while string refs offer a legacy approach that remains useful in certain scenarios. The flexibility to create refs in react using different techniques ensures that operations on an input element or any other dom element can be performed reliably across various user interfaces.
The following examples illustrate practical implementations of React createRef in diverse scenarios. Developers can observe how the ref attribute is applied across different react components to interact with the underlying dom element.
Example 1: Class Component Managing an Input Field
1import React from "react"; 2 3class InputFocus extends React.Component { 4 constructor(props) { 5 super(props); 6 this.inputRef = React.createRef(); 7 } 8 componentDidMount() { 9 // Managing focus using the current property on an input element 10 if (this.inputRef.current) { 11 this.inputRef.current.focus(); 12 console log("Current focus set on input field"); 13 } 14 } 15 render() { 16 return <input element ref={this.inputRef} />; 17 } 18} 19 20export default InputFocus;
Example 2: Function Component with Callback Refs
1import React from "react"; 2 3function CallbackInput() { 4 let inputNode = null; 5 const setInputRef = node => { 6 inputNode = node; 7 if (inputNode) { 8 console log("Callback refs react assigned a dom node:", inputNode); 9 } 10 }; 11 12 return <input element ref={setInputRef} />; 13} 14 15export default CallbackInput;
These examples demonstrate how create refs are implemented in various react components. The ref attribute applied to each react element ensures that the underlying dom element is easily accessible. Whether working with an input field in a class component or managing focus in a function component, the current property of a ref object provides a robust method to interface with a dom node. Developers can pass refs between parent component and child component to maintain consistent references, whether using callback refs, string refs, or create refs via the createref method.
React createRef serves as a powerful mechanism for managing ref attributes within react components. This blog post has examined the technical details of the createref method, highlighting its use in class components, function components, and functional components. The discussion has covered how the ref attribute created, along with the ref object that receives the current property, enables direct interaction with a dom element—be it an input element, HTML dom element, or any other dom node. By implementing callback refs and string refs as alternatives, developers can pass refs efficiently between parent component and child component, ensuring that each react component maintains a proper connection to its underlying dom element.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.