Home > front end >  How to scroll to a specific component in React JS
How to scroll to a specific component in React JS

Time:01-27

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!

CodePudding user response:

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

LastComp.js

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

On the home page, you can pass a new ref to LastComp and add the scroll method as a button event handler.

Main.js

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

export default function Main() {
  const ref = useRef(null);
  
  // event handler for the button
  const scrolltoLast = () => {
    if (ref.current) {
      ref.current.scrollIntoView();
    }
  };

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

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

CodePudding user response:

you have to name every component by unique id.

let scroll_to = document.getElementById("conponent_id").offsetTop; window.scrollTo({ behavior: "smooth", top: scroll_to, });

onclick button just run this code

CodePudding user response:

Add link to the page element

<Link to="/page#elementid">Go</Link>

Do like this, in your page component

componentDidMount() {
    let target = window.location.hash;
    target && document.querySelector(target).scrollIntoView()
}
  •  Tags:  
  • Related