score:0

Accepted answer

my recommendation is that you define all of the callbacks in the parent component, which is why i had to double check with you that the callbacks don't need to access the internal state of the child components.

i would define the props for each route individually, and include a callback along with the props.

const routes = [
  {
    path: "/cats",
    component: cat,
    callback: () => console.log("meow!")
  },
  {
    path: "/dogs",
    component: dog,
    callback: () => console.log("woof!")
  }
];

// container page
const container = () => {
  // functionality is based on the current page
  const match = useroutematch();

  // need history in order to navigate
  const history = usehistory();

  const onnavigate = () => {
    // find the config for the current page
    const currentroute = routes.find((route) => route.path === match.path);
    // do the callback
    currentroute?.callback();
    // navigate
    history.push("/complete");
  };

  return (
    <>
      <header onbuttonclick={onnavigate} />
      <switch>
        {routes.map((props) => (
          <route key={props.path} {...props} />
        ))}
      </switch>
    </>
  );
};

score:0

you can use context api and send it as prop. while sending it as a prop you can pass callback function to your onnavigate function. like this

const onnavigate = (callback) => {
  callback();

  navigate('/complete');
}

and you use it like this

<button onclick={() => onnavigate(() => console.log('blabla'))}

for context api information i recommend you to check react official documentation.


Related Query

More Query from same tag