React refs and the useRef() hook allow direct access to DOM elements. They are used when imperative actions like focusing, scrolling, or animations are required.
.current
// Creating a ref with an initial value
const ref = useRef(null);
// Accessing the current value or DOM node
ref.current;
// App.js - focusing an input using a ref
import React, { useRef } from "react";
function App() {
const inputRef = useRef(null);
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} placeholder="Type here" />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
export default App;
// Changing styles directly via ref
import React, { useRef } from "react";
function Box() {
const boxRef = useRef(null);
const changeStyle = () => {
boxRef.current.style.backgroundColor = "skyblue";
boxRef.current.style.transform = "scale(1.1)";
};
return (
<div>
<div ref={boxRef} style={{ width: "150px", height: "150px" }}></div>
<button onClick={changeStyle}>Change Style</button>
</div>
);
}
export default Box;
// Smooth scrolling using scrollIntoView
import React, { useRef } from "react";
function ScrollExample() {
const sectionRef = useRef(null);
const scrollToTarget = () => {
sectionRef.current.scrollIntoView({ behavior: "smooth" });
};
return (
<div>
<button onClick={scrollToTarget}>Scroll</button>
<div style={{ height: "500px" }}></div>
<div ref={sectionRef}>Target Section</div>
</div>
);
}
export default ScrollExample;
forwardRef() for reusable componentsref.current after component mount