React refs
Created By: chatGPT
Refs provide a way to access DOM nodes or React elements created in the render method. They offer an alternative approach to manage components when a more direct interaction is required, enabling you to bypass the component's abstract data flow. This is particularly useful for focusing on specific elements after they have been rendered, such as input fields or managing animations.
import React, { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
// Accessing the DOM node directly
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default TextInput;
In the above code, we create a functional component
TextInput
. We use the useRef
to create a ref, inputRef
, which is initiated with null
and is later attached to the input element using the ref
attribute. When the button is clicked, the focusInput
function is invoked, which calls focus()
on the input field. This demonstrates the ability to manipulate the DOM directly.import React from 'react';
class TextInputClass extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
focusInput = () => {
// Accessing the DOM node directly
this.inputRef.current.focus();
};
render() {
return (
<div>
<input ref={this.inputRef} type="text" />
<button onClick={this.focusInput}>Focus Input</button>
</div>
);
}
}
export default TextInputClass;
The second example shows how you can utilize refs in a class component by creating a
TextInputClass
. Here, React.createRef()
is used to instantiate the ref in the constructor, which is subsequently assigned to the input element. The focusInput
method similarly accesses the DOM element to set focus when the button is clicked.import React, { useRef } from 'react';
function App() {
const inputRef = useRef(null);
const handleClick = () => {
alert(inputRef.current.value);
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleClick}>Show Input Value</button>
</div>
);
}
export default App;
You can also use refs to read values directly from a component's input, as shown in this
App
function component. The handleClick
function retrieves the current value of the input field by accessing inputRef.current.value
, thereby illustrating how refs can be useful for accessing data that usually involves intermediate states.const ForwardedInput = React.forwardRef((props, ref) => {
return <input ref={ref} type="text" />;
});
function Parent() {
const inputRef = useRef(null);
const focusInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<ForwardedInput ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default Parent;
Another important aspect of refs is their compatibility with forwardRef. This allows components to pass refs through to their children. In this example,
ForwardedInput
is a functional component that receives a ref from its parent component Parent
. The parent then utilizes the focusInput
function to set focus on the forwarded input element.const ref = React.createRef();
ref.current = something; // You can also set a value anytime
console.log(ref.current); // You can log or access the current value any time
Refs are mutable, meaning you can assign different values to the same ref. This can be helpful when you need to manipulate the state or access an updated value. For example, setting
When mutating the object that a ref points to, you can access and modify its properties without triggering a re-render of the component. This behavior is particularly beneficial for performance-sensitive applications where you want to avoid unnecessary re-renders while directly manipulating state attributes or DOM elements.ref.current
at any time allows you to dynamically manage a reference without requiring a re-render.console.log(ref.current); // Access the current value
ref.current.someProperty = 'newValue'; // Mutate the object if it’s an object