添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
被表白的围巾  ·  Cannot read ...·  1 周前    · 
腹黑的领带  ·  Avoid Nesting when ...·  6 天前    · 
豪爽的麦片  ·  Out of date ...·  3 天前    · 
绅士的大脸猫  ·  用javascript ...·  4 月前    · 
俊逸的铅笔  ·  The Fourth ASHM ...·  6 月前    · 
耍酷的企鹅  ·  搜索结果-隧道网·  7 月前    · 

How to Scroll to an Element in React

Scrolling to an element or location on a page can help improve a user’s experience by directing them immediately to their area of interest, whether that’s deep in the page or simply back to the top of a page.

To help with this, we can use native browser APIs right inside of React that allow us to programmatically jump and smooth scroll for our visitor.

Table of Contents

YouTube Preview
View on YouTube

Browser APIs Available for Scrolling

Browsers largely support a few different methods of scrolling to different parts of the page using native APIs.

The ones we’ll cover include:

<button onClick={() => {
  const element = document.getElementById('my-section');
  element?.scrollIntoView({
    behavior: 'smooth'
  Jump to My Section
</button>

This can be particularly handy if you’re propagating events to a parent element or if the data is loading dynamically making it challenging to add a ref to every instance.

Part 2: Scrolling to the Top of the Page with scroll & scrollTo

Scrolling to the top of the page isn’t necessarily an element, but it’s a location on the page that’s typically marked by an element.

Historically, one way of providing a “Jump to Top” link was to use an anchor link and a fragment, which works well, but requires a little extra markup.

That works according to spec :

<button onClick={() => {
  const element = document.getElementById('my-section');
  if ( !element ) return;
  window.scroll({
    top: element.offsetTop - 20,
    behavior: 'smooth'
  Jump to My Section
</button>

Removing 20 gives us a nice little bit of padding before the element so the header isn’t completely hugging the top of the page.