Urgent.News

One page, thousands of outlets. See who else covered it.

Editions

Tech

React scrollIntoView with useRef: Scroll to an Element (2026)

You have a long form. The user hits Submit, validation fails on a field three screens down, and the error message renders somewhere they can't see. The fix is one browser API call — but where you put it, and what you pass it, is where an afternoon goes. The short answer, which is what most people are here for: import { useRef } from " react " ; function Article () { const sectionRef = useRef <…

When a user submits a form, validation errors can occur on fields far from the error message. To fix this issue, you need only one browser API call. The key is understanding how to use `ref` and `scrollIntoView` properly. The pattern is simple: place a ref on the target element, use `scrollIntoView` in the event handler, and use the `?` operator as `sectionRef.current` will be `null` until React commits the changes.

The arguments of `scrollIntoView` take an optional options object with three keys: `block`, `behavior`, and `inline`. The `block` value determines the vertical alignment, while the `behavior` value sets the scrolling method. By default, `block` aligns the element to the top, and `behavior` is set to `auto`.

To avoid common issues such as a sticky header being in the way, use the `scroll-margin-top` CSS property instead of manually calculating the position. This property allows the browser to treat the element as if it had extra space for scrolling, ensuring that your element aligns correctly with the header. This solution also works for anchored links and browser find-in-page features.

When new content is rendered, simply calling `scrollIntoView` won't work because the DOM hasn't updated yet. Instead, use `useEffect` or a callback ref to detect the new element and scroll to it. This ensures that your scrolling behavior is reliable and doesn't cause unexpected flickering or visual artifacts.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Tuesday 18 August →