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 do I zip multiple files using ReactJS?
- How can I use Yup with ReactJS?
- How do I use Yarn to install ReactJS?
- How can I convert an XLSX file to JSON using ReactJS?
- How can I use zxcvbn in a ReactJS project?
- How can I use ReactJS and ZeroMQ together to create a distributed application?
- How can I become a React.js expert from scratch?
- How do I render a component in ReactJS?
- How can I use MD5 hashing with ReactJS?
See more codes...