-1

I'm trying to create a simple action, that when the page loads, the page will scroll to a certain position.

But no matter what I do, the action does not fire.

Is there another way to do this in a React app?

for example:

window.scrollBy(0, 850);

  • Does this answer your question? [How to scroll to an element?](https://stackoverflow.com/questions/43441856/how-to-scroll-to-an-element) – 0stone0 Nov 02 '22 at 13:41

2 Answers2

0

wrap it inside useEffect:

useEffect(() => {
  window.scrollBy(0, 850);
}, []);

that way, it runs when the page mounts.

user20386762
  • 169
  • 8
0

Yes you can do this through a ref

Steps

  1. Create a ref with useRef()
  2. Assign that ref to the element you want to scroll to 3.Create a useEffect inside that useEffect add this code

useEffect(() => {
ref.current.scrollIntoView()
} ,[])

The same thing applies if you want to just scroll to a certain height, you can just wrap it in a useEffect that fires when the component is mounted