Why we use Ref in React
Using ref in React serves various purposes, particularly when direct interaction with DOM elements or React components is necessary. Here are several examples illustrating different use cases for ref in React:
1. Accessing DOM Elements
You can use ref to directly access a DOM element, which is particularly useful when you need to interact with the DOM outside the normal React flow.
import React, { useRef, useEffect } from 'react';
function TextInput() {
const inputRef = useRef(null);
useEffect(() => {
// Focus the input element when the component mounts
inputRef.current.focus();
}, []);
return <input type="text" ref={inputRef} />;
}2. Managing Focus
Refs are commonly used to manage focus, for example, to focus on an input field when a form is submitted or a modal is opened.
function LoginForm() {
const usernameRef = useRef(null);
const handleSubmit = () => {
// Focus the username input when the form is submitted
usernameRef.current.focus();
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={usernameRef} placeholder="Username" />
<button type="submit">Submit</button>
</form>
);
}3. Controlling Animations
Refs can be used to directly manipulate DOM elements for animations using libraries like GSAP or directly using the Web Animations API.
import { useRef, useEffect } from 'react';
import { gsap } from 'gsap';
function AnimatedBox() {
const boxRef = useRef(null);
useEffect(() => {
gsap.to(boxRef.current, { x: 100, duration: 2 });
}, []);
return <div ref={boxRef} style={{ width: 100, height: 100, background: 'red' }} />;
}4. Handling Text Selection
Refs can be used to programmatically select text within an input field.
function SelectableInput() {
const inputRef = useRef(null);
const handleSelect = () => {
inputRef.current.select();
};
return (
<div>
<input type="text" ref={inputRef} defaultValue="Select this text" />
<button onClick={handleSelect}>Select Text</button>
</div>
);
}5. Integrating Third-Party Libraries
When integrating non-React libraries that manipulate the DOM, refs are essential.
import { useEffect, useRef } from 'react';
import Chart from 'chart.js';
function ChartComponent() {
const chartRef = useRef(null);
useEffect(() => {
const ctx = chartRef.current.getContext('2d');
new Chart(ctx, {
type: 'bar',
data: { ... },
options: { ... }
});
}, []);
return <canvas ref={chartRef} />;
}6. Storing Previous Values
Refs can store any mutable value, not just DOM elements, making them useful for keeping track of previous values.
import { useRef, useEffect } from 'react';
function PreviousValue({ value }) {
const prevValueRef = useRef();
useEffect(() => {
prevValueRef.current = value;
}, [value]);
return <div>Previous Value: {prevValueRef.current}</div>;
}7. Triggering File Input Click
Using refs to programmatically trigger a file input click.
function FileUploader() {
const fileInputRef = useRef(null);
const handleButtonClick = () => {
fileInputRef.current.click();
};
return (
<div>
<input type="file" ref={fileInputRef} style={{ display: 'none' }} />
<button onClick={handleButtonClick}>Upload File</button>
</div>
);
}8. Measuring DOM Elements
Refs can be used to measure the dimensions or position of DOM elements.
import { useRef, useEffect, useState } from 'react';
function MeasuredDiv() {
const divRef = useRef(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
setDimensions({
width: divRef.current.offsetWidth,
height: divRef.current.offsetHeight,
});
}, []);
return (
<div>
<div ref={divRef} style={{ width: '100px', height: '100px', background: 'blue' }} />
<p>Width: {dimensions.width}, Height: {dimensions.height}</p>
</div>
);
}9. Creating Custom Form Validation
Refs can be used to access form inputs directly for validation purposes.
function CustomForm() {
const nameRef = useRef(null);
const emailRef = useRef(null);
const handleSubmit = (e) => {
e.preventDefault();
const name = nameRef.current.value;
const email = emailRef.current.value;
if (!name || !email) {
alert('All fields are required!');
} else {
alert('Form submitted successfully!');
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={nameRef} placeholder="Name" />
<input type="email" ref={emailRef} placeholder="Email" />
<button type="submit">Submit</button>
</form>
);
}
10. Accessing Child Components
Refs can be used to access methods or properties of child components.
import React, { useRef } from 'react';
function ChildComponent() {
const childMethod = () => {
alert('Child method called!');
};
return <div>Child Component</div>;
}
function ParentComponent() {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.childMethod();
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Call Child Method</button>
</div>
);
}
export default ParentComponent;
These examples demonstrate the flexibility and power of using refs in React for various scenarios, from simple DOM manipulations to integrating complex third-party libraries and managing component states.