React is a JavaScript library for building user interfaces, and it doesn't have a built-in feature for listening to history events. However, you can use the history
library, which is part of the react-router-dom
package, to listen for changes to the browser's history and perform actions in response.
Here is an example of how you can use the history
library to listen for changes to the browser's history in a React component:
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
useEffect(() => {
const unlisten = history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}`);
console.log(`The last navigation action was ${action}`);
});
return () => {
unlisten();
}
}, [history]);
return (
// component JSX goes here
);
}
The history.listen
function takes a callback function as an argument, which will be called any time the location changes. The callback receives the new location and the action that caused the change as arguments. The useEffect
hook is used to set up the event listener when the component mounts, and the returned function is used to clean up the event listener when the component unmounts.