← Back to Chapters

Refs & DOM Manipulation

? Refs & DOM Manipulation

? Quick Overview

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.

? Key Concepts

  • Refs persist across re-renders
  • Stored value is available on .current
  • Ref updates do not cause re-renders
  • Best suited for DOM access and mutable values

? Syntax & Theory

? View Code Example
// Creating a ref with an initial value
const ref = useRef(null);

// Accessing the current value or DOM node
ref.current;

? Accessing an Input Element

? View Code Example
// 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;

? Controlling DOM Styles

? View Code Example
// 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;

? Scrolling to a Section

? View Code Example
// 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;

? Tips & Best Practices

  • Use refs for focus, scroll, and animations
  • Avoid refs for rendering logic or data flow
  • Prefer state when UI updates are required
  • Combine with forwardRef() for reusable components

? Try It Yourself

  1. Auto-focus the first input on page load
  2. Create a scroll-to-top button
  3. Trigger a CSS animation using refs
  4. Log ref.current after component mount