score:2

Accepted answer

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

score:0

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()
}

score:0

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


Related Query

More Query from same tag