score:2

Accepted answer

you cannot pass refs as props to other components with the name prop without using forwardref on the commponent. you need to assign another name to it in order for it to work, for example innerrefs.

also to pass on refs as prop to the route component, make use of render prop method

app.tsx

import react, { useeffect, useref } from "react";
import { browserrouter, route, navlink, uselocation } from "react-router-dom";
import home from "./pages/home";
import "./styles.css";

const header = ({ innerrefs }) => {
  const location = uselocation();

  useeffect(() => {
    console.log("location", location.pathname);
    switch (location.pathname) {
      case "/about":
        scrollsmoothhandler(innerrefs.aboutref);
        break;
      case "/contact":
        scrollsmoothhandler(innerrefs.contactref);
        break;
      case "/hero":
        scrollsmoothhandler(innerrefs.heroref);
        break;

      default:
        scrollsmoothhandler(innerrefs.homeref);
        break;
    }
  }, [location, innerrefs]);

  const scrollsmoothhandler = innerref => {
    console.log("triggered.");
    console.log(innerref.current);
    innerref.current.scrollintoview({ behavior: "smooth" });
  };

  return (
    <>
      <navlink to="/hero" activeclassname="selected">
        hero
      </navlink>
      <navlink to="/about" activeclassname="selected">
        about
      </navlink>
      <navlink to="/contact" activeclassname="selected">
        contact
      </navlink>
    </>
  );
};

function app() {
  const homeref = useref(null);
  const heroref = useref(null);
  const aboutref = useref(null);
  const contactref = useref(null);

  return (
    <div ref={homeref} classname="app">
      <browserrouter>
        <header innerrefs={{ aboutref, contactref, heroref, homeref }} />
        <route
          exact
          to="/"
          render={routeprops => (
            <home
              {...routeprops}
              innerrefs={{ aboutref, contactref, heroref, homeref }}
            />
          )}
        />
        // more routes here.
      </browserrouter>
    </div>
  );
}

export default app;

home.tsx

import react, { fragment, forwardref, useref } from "react";
import "../styles.css";

const hero = forwardref((props, ref) => {
  return (
    <section ref={ref}>
      <h1>hero section</h1>
    </section>
  );
});

const about = forwardref((props, ref) => {
  return (
    <section ref={ref}>
      <h1>about section</h1>
    </section>
  );
});

const contact = forwardref((props, ref) => {
  return (
    <section ref={ref}>
      <h1>contact section</h1>
    </section>
  );
});

function home({ innerrefs }) {
  return (
    <fragment>
      <hero ref={innerrefs.heroref} />
      <about ref={innerrefs.aboutref} />
      <contact ref={innerrefs.contactref} />
    </fragment>
  );
}

export default home;

working demo here


Related Query

More Query from same tag