Skip to content
Advertisement

How to scroll to the desired element in React?

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 component 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>

Advertisement

Answer

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> 
      </>
   )
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement