React: [useRef, scrollIntoView,] How to only autoscroll a specific div inside of an overflowing page?

Asked
Active3 hr before
Viewed126 times

9 Answers

react
90%

The page loads, and both the page and the nested scrolling div auto scroll.,What I'm trying to do is only scrollIntoView the overflowing div I have set as my ref., What does one need to know to learn to improvise with other musicians?

Try this:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
   });
88%

#javascript #promises #howto ,Saved by @davidTheNerdy #javascript #useref , #javascript #nodejs #commandline

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
   });
load more v
72%

There is a method called scrollIntoView that exists on HTML elements that we can use that is supported on all modern browsers. This method will scroll the element’s parent container so that it becomes visible to a user.,In this case, we want to automatically scroll the problem field into the users view to improve the user experience.,Note that scrollIntoViewOptions isn’t available on IE and Safari at the time of writing this post. So, we won’t see this minor improvement in those browsers.

const Field = ({ ... }: FieldProps) => {
  const fieldRef = React.useRef<HTMLInputElement>(null);  return (
    <div className="field" ref={fieldRef}>      ...
    </div>
  );
};
load more v
65%

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Pretag
 Pretag team - issue, fix, solve, resolve
40%

But how do we grab a user’s attention for something that isn’t visible in the current part of the viewport it’s currently looking at. We can utilize a very handy browser API for that, called Element.scrollIntoView(). Which does exactly what it says it does with a few nice options to modify its behavior.,For most use cases, this is sufficient. But sometimes you’ll would like to have a nice animation while scrolling. Luckily you can pass additional options to the method to do exactly that.,Before diving into the React implementation, let’s try out the API on a simple HTML list with vanilla JavaScript.

<article>
   <h1 id="title">An interesting article for Latin readers</h1>
   <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit
      amet luctus neque. Etiam eu quam lacinia, placerat sem ut, interdum
      risus. Quisque ut feugiat mauris. Aenean euismod fermentum facilisis.
      Donec ultricies maximus elit, sit amet convallis urna rhoncus vitae.
      Aliquam bibendum turpis et felis blandit commodo. Donec egestas neque
      non elit laoreet, faucibus tempor ante gravida.
   </p>
   <p>
      Duis in ante turpis. Phasellus dignissim tellus et nunc lacinia
      elementum. Sed venenatis tincidunt justo. Praesent sed purus facilisis,
      porttitor ligula in, mattis velit. Curabitur non pellentesque nunc. Duis
      elit urna, bibendum et purus nec, maximus imperdiet mauris. Cras
      euismod, leo id vehicula vulputate, nibh massa tincidunt justo, sit amet
      fringilla quam orci pellentesque enim.
   </p>
   <p>...</p>
</article>
load more v
22%

The implementation to scroll from outside the list to an item looks as follows:,The implementation to scroll from within the list to an item looks as follows:,Each list item has an artificial height; otherwise the scrolling wouldn't work. Let's see the implementation.

A brief tutorial which shows you two use cases on how to scroll to an item within a list of items in a . We will use the native browser API to scroll to our React element with a button click. It's up to you how to trigger the event in the end. For both use cases, we will start with the same React list component that renders a list of items from an array of objects:

import React from 'react'; const list = [  {    id: 'a',    firstname: 'Robin',    lastname: 'Wieruch',    year: 1988,  },  {    id: 'b',    firstname: 'Dave',    lastname: 'Davidds',    year: 1990,  },  ...]; const List = () => (  <ul>    {list.map(item => {      return (        <li          key={item.id}          style={{ height: '250px', border: '1px solid black' }}        >          <div>{item.id}</div>          <div>{item.firstname}</div>          <div>{item.lastname}</div>          <div>{item.year}</div>        </li>      );    })}  </ul>); export default List;
import React from 'react'; const list = [  {    id: 'a',    firstname: 'Robin',    lastname: 'Wieruch',    year: 1988,  },  {    id: 'b',    firstname: 'Dave',    lastname: 'Davidds',    year: 1990,  },  ...]; const List = () => (  <ul>    {list.map(item => {      return (        <li          key={item.id}          style={{ height: '250px', border: '1px solid black' }}        >          <div>{item.id}</div>          <div>{item.firstname}</div>          <div>{item.lastname}</div>          <div>{item.year}</div>        </li>      );    })}  </ul>); export default List;

The implementation to scroll from within the list to an item looks as follows:

import React from 'react'; const list = [ ... ]; const List = () => (  <ul>    {list.map(item => {      const ref = React.createRef();       const handleClick = () =>        ref.current.scrollIntoView({          behavior: 'smooth',          block: 'start',        });       return (        <li          key={item.id}          ref={ref}          style={{ height: '250px', border: '1px solid black' }}        >          <div>{item.id}</div>          <div>{item.firstname}</div>          <div>{item.lastname}</div>          <div>{item.year}</div>          <button type="button" onClick={handleClick}>            Scroll Into View          </button>        </li>      );    })}  </ul>); export default List;
import React from 'react'; const list = [ ... ]; const List = () => (  <ul>    {list.map(item => {      const ref = React.createRef();       const handleClick = () =>        ref.current.scrollIntoView({          behavior: 'smooth',          block: 'start',        });       return (        <li          key={item.id}          ref={ref}          style={{ height: '250px', border: '1px solid black' }}        >          <div>{item.id}</div>          <div>{item.firstname}</div>          <div>{item.lastname}</div>          <div>{item.year}</div>          <button type="button" onClick={handleClick}>            Scroll Into View          </button>        </li>      );    })}  </ul>); export default List;

The implementation to scroll from outside the list to an item looks as follows:

import React from 'react'; const list = [ ... ]; const List = () => {  const refs = list.reduce((acc, value) => {    acc[value.id] = React.createRef();    return acc;  }, {});   const handleClick = id =>    refs[id].current.scrollIntoView({      behavior: 'smooth',      block: 'start',    });   return (    <div>      <ul>        {list.map(item => (          <li key={item.id}>            <button              type="button"              onClick={() => handleClick(item.id)}            >              Scroll Item {item.id} Into View            </button>          </li>        ))}      </ul>       <ul>        {list.map(item => (          <li            key={item.id}            ref={refs[item.id]}            style={{ height: '250px', border: '1px solid black' }}          >            <div>{item.id}</div>            <div>{item.firstname}</div>            <div>{item.lastname}</div>            <div>{item.year}</div>          </li>        ))}      </ul>    </div>  );}; export default List;
import React from 'react'; const list = [ ... ]; const List = () => {  const refs = list.reduce((acc, value) => {    acc[value.id] = React.createRef();    return acc;  }, {});   const handleClick = id =>    refs[id].current.scrollIntoView({      behavior: 'smooth',      block: 'start',    });   return (    <div>      <ul>        {list.map(item => (          <li key={item.id}>            <button              type="button"              onClick={() => handleClick(item.id)}            >              Scroll Item {item.id} Into View            </button>          </li>        ))}      </ul>       <ul>        {list.map(item => (          <li            key={item.id}            ref={refs[item.id]}            style={{ height: '250px', border: '1px solid black' }}          >            <div>{item.id}</div>            <div>{item.firstname}</div>            <div>{item.lastname}</div>            <div>{item.year}</div>          </li>        ))}      </ul>    </div>  );}; export default List;
load more v
60%

Scrolling is defined as sliding-effect movement on images, text, or graphics across the computer display screen horizontally, vertically, or both. When developing web pages, you can enable scrolling by default for the complete webpage or only the areas where it is required.,Continuing the previous example: After reading all the information, you can exit the web page by clicking the Exit button. This opens up a dialog box that shows a goodbye message. While the pop-up is present on the screen, make sure that the scroll bar behind the webpage is disabled. Below is the code for creating the button and popup:,Single-direction scrolling can be applied when the scroll movement is either horizontal or vertical.

1

<body>
   2 <div id=”menu”></div>
   3</body>
load more v
48%

Tracking viewport/element scroll position could be vastly useful and for the most part, the only way to enrich your web project with cool dynamic features, like:,The next part is straight forward, we check if the user requested the scroll position of the entire page or any specific element inside it.,Display viewport scroll position

import {
   useRef,
   useLayoutEffect
} from 'react'

const isBrowser = typeof window !== `undefined`

function getScrollPosition({
   element,
   useWindow
}) {
   if (!isBrowser) return {
      x: 0,
      y: 0
   }

   const target = element ? element.current : document.body
   const position = target.getBoundingClientRect()

   return useWindow ?
      {
         x: window.scrollX,
         y: window.scrollY
      } :
      {
         x: position.left,
         y: position.top
      }
}

export function useScrollPosition(effect, deps, element, useWindow, wait) {
   const position = useRef(getScrollPosition({
      useWindow
   }))

   let throttleTimeout = null

   const callBack = () => {
      const currPos = getScrollPosition({
         element,
         useWindow
      })
      effect({
         prevPos: position.current,
         currPos
      })
      position.current = currPos
      throttleTimeout = null
   }

   useLayoutEffect(() => {
      const handleScroll = () => {
         if (wait) {
            if (throttleTimeout === null) {
               throttleTimeout = setTimeout(callBack, wait)
            }
         } else {
            callBack()
         }
      }

      window.addEventListener('scroll', handleScroll)

      return () => window.removeEventListener('scroll', handleScroll)
   }, deps)
}
load more v

Other "react-undefined" queries related to "React: [useRef, scrollIntoView,] How to only autoscroll a specific div inside of an overflowing page?"