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 can I convert an XLSX file to JSON using ReactJS?
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How do I create a zip file using ReactJS?
- How can I use ReactJS Zustand to manage state in my application?
- How can I use React.js to parse XML data?
- How do I create a ReactJS tutorial?
- How can I use the useReducer hook in a React application?
- How do I implement pagination in ReactJS?
- How can I use ReactJS PropTypes to validate my components?
- How can I connect a MySQL database to a React.js application?
See more codes...