Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change route outside react function component and let react-router know about it?

I'm using CRA (create-react-app) and react-router.

However, I also use an event-driven system to manage states and messaging.

Now I need to change URL somewhere outside react function components. Thus I can't use useHistory.

Is there a way to change the URL/Route and let react router know about it?

like image 728
Hossein Fallah Avatar asked Oct 25 '25 04:10

Hossein Fallah


1 Answers

Create a function that will dispatch a Custom Event after clicking on the link. In the React application, implement an event listener for it and update the router's history.

 //Dispatch a custom event

 function changeRoute(path) {
    const { CustomEvent } = window;
    const event = new CustomEvent('changeroute', { detail: path });
    window.dispatchEvent(event);
 }

 //In the React App, listen for the event and update the router (instance of the BrowserRouter)

function handleRouteChange(router) {
     window.addEventListener('changeroute', e => {
           const { detail: path } = e;
           router.history.push(path);
     },true)
}
like image 188
Hoyen Avatar answered Oct 26 '25 20:10

Hoyen