Search code examples
javascriptreactjsjs-scrollintoview

scrollIntoView() scroll only in div in React


I have a container with some elements (see image below), and whenever I click on one of the elements, I would like them for the user to be in the center of the container.

Container with my elements

My container where I would like to scroll to an element

I am using a ref array for all the elements, and whenever I click on an element I will call the scrollIntoView() function.

        itemsRef.current[curVideoPos]?.scrollIntoView({
            block: "center",
            inline: "nearest",
        });

The scroll function work how I want it to be, but the only problem is that the entire page gets also moved(scrolled). So what do I need to do so that the scrollIntoView() function only scrolles in on container and not the entire page?


Solution

  • You should do it like this:

    element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' })