Master react-scroll: Smooth Scrolling, ScrollSpy & Setup
A compact, practical guide to install, configure, and use react-scroll for reliable, animated single-page navigation in React apps.
Introduction: what react-scroll solves and when to use it
Single-page applications benefit from smooth, predictable navigation between sections. react-scroll is a lightweight, battle-tested library that provides animated scrolling, scroll-to-element utilities, and ScrollSpy-like features for React. It handles anchors, easing, offsets, and programmatic control without reinventing the wheel.
Use react-scroll when you want a declarative way to wire navigation links to page sections, create animated scroll behaviors for hero–to–section transitions, or implement section-aware navigation that highlights the active link. It integrates cleanly with functional components and works with client-side routing when you manage scroll positions appropriately.
This guide walks through installation, basic usage, common props, ScrollSpy implementation, programmatic control, and advanced tips for performance and accessibility so you can ship reliable in-page navigation quickly.
Installation & setup
Install react-scroll via npm or yarn. It’s small and has no runtime CSS requirements—only the JS module. If you prefer a starter walkthrough, see this react-scroll tutorial on Dev.to for a step-by-step example.
- npm: npm install react-scroll
- yarn: yarn add react-scroll
Once installed, import the components you need from react-scroll. Typical imports are Link (for navigation), Element (to mark scroll targets), and scroller/animateScroll for programmatic control. These exports let you keep markup declarative while using functions for advanced behaviors.
If you’re integrating with a router (React Router, Next.js, etc.), decide whether to handle navigation via route changes or keep on-page anchors. For pure on-page SPA navigation, react-scroll works out of the box. For route-based navigation, use programmatic scroll after route change to avoid conflicting scroll positions.
Quick reference: Follow this react-scroll setup and tutorial on Dev.to for a compact example and full code snippets.
Basic usage: Link, Element, and a minimal example
react-scroll uses two primary primitives: Link and Element. Link renders a clickable element that animates scrolling to the named Element. Element wraps the section you want to target. This pattern keeps your navigation semantic and easy to manage.
The most common pattern: add <Element name="section1"> around your section and use <Link to="section1" smooth={true}> in your nav. The props let you control duration, easing, and offset for sticky headers.
// Minimal example (JSX)
import { Link, Element } from 'react-scroll'
<h2>About</h2>
<p>Content...</p>
This pattern supports any element (div, section, header) and works with styled components or CSS modules. Because react-scroll computes target positions in the DOM, ensure the target element exists and is not deferred by lazy loading when you call programmatic scrolls.
Using offset is essential when you have a fixed header. For example, <Link to="about" smooth={true} offset={-80}> will stop 80 pixels above the target. That keeps the section title visible below the fixed header.
Smooth scroll options and animations
react-scroll exposes options to fine-tune animations: duration, delay, smooth (boolean or easing function), offset, and more. With these you can create snappy micro-interactions or slower, cinematic transitions depending on UX needs.
For smooth easing, pass a string (e.g., ‘easeInOutQuart’) or a custom function. Durations are in milliseconds. Combining delay and duration helps coordinate multiple animations—useful when you animate content into view after scroll completes.
Note: Overly long durations can feel sluggish, especially on mobile. Test durations across actual devices. When animating large jumps (many viewport-heights), prefer easing over extremely long durations so users retain a sense of control.
- Common props: smooth, duration, offset, delay, isDynamic
Also consider isDynamic (for content that changes height) and spy (used with ScrollSpy). When content above a target changes size, isDynamic forces recalculation of positions before each scroll—recommended for dynamic layouts.
ScrollSpy & navigation highlighting
ScrollSpy is the behavior where the navigation indicates the active section as you scroll. react-scroll supports this via the spy prop on Link plus the activeClass attribute. It listens to scroll events and toggles classes on the active Link automatically.
Set spy={true} and provide activeClass="active". The library calculates which Element is currently visible based on offsets. Combine this with CSS transitions for smooth highlighting. This works well for table-of-contents or side navigation UIs.
Edge cases: If sections are smaller than the viewport or if multiple sections are partially visible, tweak the offset or use a custom activeClass logic to match your UX requirements. Also debounce heavy scroll handlers where you also run analytics or animations.
// Example Link with spy
Features
Programmatic scrolling and scroll-to-element
Beyond Link/Element, react-scroll exposes imperative utilities like scroller.scrollTo() and animateScroll.scrollTo(). These are useful when you need to trigger scrolling from event handlers, after async loads, or on route changes.
Example: After fetching content, you might want to jump to the first error message. Call scroller.scrollTo('error-1', { duration: 400, smooth: true }). If you need absolute scrolling, use animateScroll.scrollTo(y) with a pixel value.
Remember to guard programmatic calls until the target DOM nodes exist. If you call scroll before render, results will be inconsistent. When working with React Router, call scroll logic in a useEffect that runs after navigation completes.
// Programmatic example
import { scroller } from 'react-scroll'
scroller.scrollTo('pricing', {
duration: 600,
delay: 0,
smooth: 'easeInOutQuart',
offset: -60
})
Advanced usage & performance tips
For large pages, reduce scroll event work by delegating heavy calculations to requestAnimationFrame or throttling. react-scroll is lightweight, but your app-level handlers can slow scroll performance. Use passive event listeners where possible and avoid layout thrashing inside scroll handlers.
If you employ server-side rendering (SSR), avoid running react-scroll code during the server pass—guard DOM calls with checks for window or useEffect hooks that run only on the client. This prevents hydration mismatches and runtime errors during SSR.
For accessibility, ensure keyboard users can focus sections. Use semantic anchors and skip links when appropriate. If you animate focus alongside scroll, manage focus order so screen readers follow the user’s context. Smooth scrolling should not break assistive navigation—test with screen readers and keyboard-only navigation.
Troubleshooting common issues
If your Link doesn’t scroll, confirm the Element name matches the Link’s to prop exactly. Check for typos and dynamic rendering: if the Element is conditionally rendered, ensure it exists before you call scroll. For programmatic calls, wait for layout to stabilize.
Sticky headers often cause off-by-some pixels issues; fix them with the offset prop. If multiple scroll libraries clash (e.g., fullPage.js or custom smooth-scroll libraries), disable one—only one handler should manage scroll to avoid fighting for control.
On mobile browsers, momentum scrolling and heavy JS can cause jumpiness. Keep durations moderate, avoid animating large layout changes during scroll, and test on mid-range devices. If you see strange behavior after dynamic content loads, call scroller.refresh() or re-render with isDynamic enabled.
Backlinks & Further Reading
For a practical walk-through and example source code, see this detailed react-scroll tutorial. It covers many of the patterns shown above in a runnable demo.
If you seek a canonical setup or alternate examples, the tutorial at the link also includes sample projects and explained trade-offs to speed up implementation.
Semantic core (keyword clusters)
Primary (high intent):
- react-scroll
- react-scroll smooth scroll
- React smooth scrolling
- react-scroll installation
- React scroll navigation
Secondary (medium intent):
- react-scroll tutorial
- React scroll spy
- react-scroll example
- React animated scroll
- react-scroll setup
Clarifying / long-tail (supporting):
- react-scroll scroll to element
- react-scroll getting started
- React single page navigation
- react-scroll advanced usage
- react-scroll programmatic scroll scroller
Use these phrases naturally across headings, code captions, and alt text to improve topical relevance and featured-snippet probability.
FAQ
How do I install and set up react-scroll?
Install with npm install react-scroll or yarn add react-scroll, then import components like Link and Element. Wrap target sections with <Element name="id"> and use <Link to="id" smooth={true}> in your navigation. For a hands-on walkthrough, see this react-scroll tutorial.
How can I highlight the active nav item while scrolling (ScrollSpy)?
Use spy={true} and activeClass="your-active-class" on Links. react-scroll listens to scroll events and toggles the active class based on which Element is in view. Tune offset and isDynamic for precise behavior with sticky headers or dynamic content.
How do I scroll programmatically to an element?
Use the imperative API: scroller.scrollTo('name', options) or animateScroll.scrollTo(y). Ensure the target Element exists (call after render or in a useEffect). Pass options like duration, smooth, and offset to control the animation.
