copser
copser

Reputation: 2641

scroll to element on reload page react

I'm trying to figure out how to scroll to the element after page reloads. I'm trying to ref the element and scroll to it after page reloads.

My current example will just scroll to the end of the page

const transactionRef = useRef(null)
const scrollToElemet = () => {
    transactionRef.current.scrollIntoView({ block: 'end', behavior: 'smooth' });
  }

  useEffect(scrollToElemet)

return (
  <div ref={transactionRef}></div>
)

How can I calculate the position of the element and scroll to it on page reload? Thanks

Upvotes: 0

Views: 1938

Answers (2)

Dennis Vash
Dennis Vash

Reputation: 53874

Adding this answer because querying the DOM in react is an anti-pattern:

export default function App() {
  const footerRef = useRef();

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

  return (
    <>
      <div className="main">Main</div>
      <div ref={footerRef} className="footer">
        Footer
      </div>
    </>
  );
}

Edit Q-60229673-FooterRef

Upvotes: 1

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

I would say, add an element at the bottom of your page and then use that element to scroll. Here is a sample

https://codesandbox.io/s/jolly-dhawan-k7q8b?fontsize=14&hidenavigation=1&theme=dark

Also, you need to pass [] as second argument so it only scroll on first mount otherwise it will keep on scrolling down to bottom on every change or on every render.

function App() {
  const [checked, setChecked] = useState(false);
  useEffect(() => {
    document.getElementById("footer").scrollIntoView();
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <span onClick={() => setChecked(v => !v)}>{checked ? "Enable" : "Disable"}</span>
      <h2>Start editing to see some magic happen!</h2>
      <div className="main">Main</div>
      <div id="footer" className="footer">
        Footer
      </div>
    </div>
  );
}

Upvotes: 1

Related Questions