Getting the current route in React router
In this tutorial, we are going to learn about how to get the current route (path) from a url in react router.
Getting current route using hooks
With the react router v5, we can use the useLocation()
hook to get the current route path in a router component.
Example:
import React from "react";
import { useLocation } from "react-router-dom";
export default function About() {
const location = useLocation();
console.log(location.pathname); // path is /contact
return (
<div>
<h2>Contact</h2>
</div>
);
}
In the above code, we first imported the useLocation
hook from the react-router-dom
package, then inside the About
component we accessed the current route using location.pathname
property.
Getting the current route in class components
In class components, you can get the current route by using this.props.location.pathname
property.
import React from "react";
class About extends React.Component {
render() {
console.log(this.props.location.pathname); // path is /about return (
<div>
<h2>About</h2>
</div>
);
}
}
export default About;
If you are using the react-router latest version, you need to use withRouter()
higher-order component.
import React from "react";
import { withRouter } from "react-router-dom";
class About extends React.Component {
render() {
console.log(this.props.location.pathname); // path is /about return (
<div>
<h2>About</h2>
</div>
);
}
}
export default withRouter(About);