admin管理员组

文章数量:1356334

I have a question - I have a list that is in a separate popup with a limited height. After this height, a side scroll appears. I need to scroll to a specific element automatically when that ponent is rendered. How to implement it? I just can't figure out how to scroll to a certain element.

Below is an example of my jsx code

<ul className={style.list}>
        {itemsForRender?.length ? (
          itemsForRender.map((item) => (
            <li className={style.item} key={item.id}>
              <button
                type="button"
                className={
                  activeItem === item.id
                    ? `${style.button} ${style.activeClass}`
                    : style.button
                }
                onClick={() => selectItem(item.id)}
              >
                {item.name}
              </button>
            </li>
          ))
        ) : (
          <p className={style.searchSubtitle}>
            Just text
          </p>
        )}
      </ul>

I have a question - I have a list that is in a separate popup with a limited height. After this height, a side scroll appears. I need to scroll to a specific element automatically when that ponent is rendered. How to implement it? I just can't figure out how to scroll to a certain element.

Below is an example of my jsx code

<ul className={style.list}>
        {itemsForRender?.length ? (
          itemsForRender.map((item) => (
            <li className={style.item} key={item.id}>
              <button
                type="button"
                className={
                  activeItem === item.id
                    ? `${style.button} ${style.activeClass}`
                    : style.button
                }
                onClick={() => selectItem(item.id)}
              >
                {item.name}
              </button>
            </li>
          ))
        ) : (
          <p className={style.searchSubtitle}>
            Just text
          </p>
        )}
      </ul>
Share Improve this question asked Jul 5, 2022 at 10:41 user18119766user18119766
Add a ment  | 

4 Answers 4

Reset to default 2

you can use scrollIntoView() where you want scroll automatically

document.getElementById(element-id).scrollIntoView({behavior: 'smooth'})

you can use this in a useEffect() to run it when ponent is rendered

I hope this would be helpful. thanks

const scrollRef = useRef([]);

useEffect(() => {
      // here you call the function scrollToSection and pass the id where you want to scroll
    }, [])

const scrollToSection = id => {
  if (scrollRef.current.length) {
    scrollRef.current[id].scrollIntoView();
  }
};

<ul className={style.list}>
  {itemsForRender?.length ? (
    itemsForRender.map((item) => (
      <li className={style.item} ref={ref => (scrollRef.current[item.id] = ref)} key={item.id}>
        <button
          type="button"
          className={
            activeItem === item.id
              ? `${style.button} ${style.activeClass}`
              : style.button
          }
          onClick={() => selectItem(item.id)}
        >
          {item.name}
        </button>
      </li>
    ))
  ) : (
    <p className={style.searchSubtitle}>
      Just text
    </p>
  )}
</ul>

Use this code :

const ScrollDemo = () => {
   const myRef = useRef(null)

   const executeScroll = () => myRef.current.scrollIntoView()    
   // run this function from an event handler or an effect to execute scroll 

   return (
      <> 
         <div ref={myRef}>Element to scroll to</div> 
         <button onClick={executeScroll}> Click to scroll </button> 
      </>
   )
}

I had used Element.scrollIntoView() Method in React with making a reference of element i want to scroll to, here is the example:

function TestComponent() {
  const testRef = useRef(null);
  const scrollToElement = () => testRef.current.scrollIntoView();
  // Once the scrollToElement function is run, the scroll will show the element
  return (
    <>
      <div ref={testRef}>Element you want to view</div>
      <button onClick={scrollToElement}>Trigger the scroll</button>
    </>
  );
}

本文标签: javascriptHow to scroll to the desired element in ReactStack Overflow