React router is react library that allows for easy navigation on react project/website. Get the current route by doing the following. Call useLocation()
const location = useLocation();
Then access the location by using location.pathname.
Below is an example piece of code.
Some code...
import React from 'react'
import { useLocation } from 'react-router-dom';
function LogRoute() {
const location = useLocation();
console.log(location.pathname);
return (
<div>
{location.pathname}
</div>
)
}
Getting the location will allow more finely grained control in your application. Here are a couple reasons why this is useful.
- Having the route location allows dynamic styling such as on the navigation links on this page.
- It can make component reuse easier by getting the location independently of props being passed
Some code...
import React from 'react'
import { useLocation } from 'react-router-dom'
function Greetings() {
const location = useLocation();
let greetings = location.pathname === 'signup' ? 'Hello, please sign up' : 'Hello'
return (
<div>
{greetings}
</div>
)
}
The example above shows a dynamic greeting based on the current URL a user is on. While this example is silly, other times it will be invaluable when determining behavior of components based on which page they are on.