Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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> 
      </>
   )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading