Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to a specific component in React JS

I've built a website using React (without any HTML) and I've split every page into smaller components. Let's say that I have for example the main page, and in the first component (the main section which is located at the top of the page) I have a button, and when I click on it I want it to take me to the last component of the page (which is located at the very bottom). I want something similar to the HTML "on click scroll to ID element".

How can I achieve that? Keep in mind that for every component I've created a separate js file.

Thank you!

like image 655
Tomuta Razvan Avatar asked Sep 15 '25 13:09

Tomuta Razvan


1 Answers

You can achieve it using react hooks. You have to refactor the last component a bit, as to forward a ref. You can expose the scroll method in the LastComp with useImperativeHandle hook.

LastComp.js

import { useImperativeHandle, forwardRef, useRef } from "react";

const LastComp = forwardRef((props, ref) => {
  const compRef = useRef();
  useImperativeHandle(ref, () => ({
    scrollIntoView: () => {
      compRef.current.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  }));
  return (
    <div style={{ height: "600px", backgroundColor: "gray" }} ref={compRef}>
      Body of the last component
    </div>
  );
});

export default LastComp;

In the FirstComp you can pass the ref as refToLastComp and call the method we exposed in the LastComp.

FirstComp.js

const FirstComp = ({ refToLastComp }) => {
  const scrolltoLast = () => {
    if (refToLastComp.current) {
      refToLastComp.current.scrollIntoView();
    }
  };

  return (
    <div
      style={{
        height: "600px",
        backgroundColor: "tomato"
      }}
    >
      <button onClick={scrolltoLast}>Scroll to Last</button>
      First
    </div>
  );
};

export default FirstComp;

On the main page, you can create and pass a new ref to LastComp and FirstComp.

Main.js

import { useRef } from "react";
import FirstComp from "./FirstComp";
import SecondComp from "./SecondComp";
import LastComp from "./LastComp";

export default function Main() {
  const ref = useRef(null);

  return (
    <>
      <FirstComp refToLastComp={ref} />
      <SecondComp />
      <LastComp ref={ref} />
    </>
  );
}

It doesn't matter where the component is located, it can be anywhere on the home page. when you click on the button it will scroll to the component to view (using scrollIntoView).

Code Sandbox

like image 156
Amila Senadheera Avatar answered Sep 17 '25 03:09

Amila Senadheera