Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ref scrollIntoView does not work with behavior smooth on react

I am creating a component that will hold a dynamic list of elements and for styling reasons, I need to keep the title for each section in a sticky nav menu. As the user scrolls up and down the list of sections I need to apply styling rules and also bring the same section in the menu nav into view so I've tried using scrollIntoView with the menu section ref.

My inner workings and logic seem to work as expected, there is however an issue - unless I inspect or use a refresh on the page, the function for scrollIntoView does not execute on every state change

const scrollTo = (ref) => {
  ref.current.scrollIntoView({ behavior: "smooth", inline: "center" });
};

To keep things short I have added my workings into this codesandbox

Any help would be greatly appreciated as I've run out of ideas.

Thanks

Edit:

The scrolling behaviour seems to work as expected if I remove the "smooth" option in the behavior parameter from the scrollIntoViewOptions options. It does however look jumpy.

const scrollToMenu = (ref) => {
  ref.current.scrollIntoView({ inline: "center", });
};
like image 588
Gareth Townsend Avatar asked Apr 25 '26 04:04

Gareth Townsend


1 Answers

Curiously, scrollIntoView() doesn't work when called synchronously, but in my case, putting it into a setImmediate() worked fine:

const scrollToMenu = (ref) => {
    setImmediate(() => ref.current.scrollIntoView({ inline: "center", }));
};
like image 160
Jthorpe Avatar answered Apr 26 '26 18:04

Jthorpe