reactjsHow can I get the current route in ReactJS?
In order to get the current route in ReactJS, you can use the useLocation hook from the react-router-dom package.
import { useLocation } from 'react-router-dom';
const MyComponent = () => {
const { pathname } = useLocation();
console.log(pathname);
}
// Output: '/about'
The useLocation hook returns an object with the following properties:
pathname: The path of the current location (e.g./about).search: The query string of the current location (e.g.?foo=bar).hash: The hash of the current location (e.g.#foo).state: The state of the current location (e.g.{ foo: 'bar' }).
It is also possible to get the current route using the withRouter higher-order component from react-router-dom:
import { withRouter } from 'react-router-dom';
const MyComponent = ({ location }) => {
console.log(location.pathname);
}
export default withRouter(MyComponent);
// Output: '/about'
The withRouter higher-order component passes the location object as a prop to the wrapped component.
Helpful links
More of Reactjs
- How do I create a zip file using ReactJS?
- How can I become a React.js expert from scratch?
- How do I use Yup validation with ReactJS?
- How do I zip multiple files using ReactJS?
- How can I use Yup with ReactJS?
- How do I set the z-index of a ReactJS component?
- How can I use a ReactJS XML editor?
- How can I convert an XLSX file to JSON using ReactJS?
- How can I use ReactJS Zustand to manage state in my application?
- How do I create a video with ReactJS?
See more codes...