Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

2 Answers

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

like image 124
Ali Javadpour Avatar answered Sep 13 '25 01:09

Ali Javadpour


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>
like image 33
Ahmad Avatar answered Sep 13 '25 01:09

Ahmad