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?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With