React ~ Router ~ Customizing Link - rohit120582sharma/Documentation GitHub Wiki
We want to add a “>” to the front of whatever Link is active.
As we are already familiar that Route has a location checker and first instinct might be to use Routes render prop. The problem with this is, a Route using render prop will only match if the path prop matched the app’s current location.
Route has another prop - children. It is similar to render. However, children gets rendered regardless of whether the path is matched with the location or not.
const CustomLink = ({ children, to, exact }) => {
return (
<Route path={to} exact={exact} children={(props) => (
<div className={props.match ? 'active' : ''}>
{props.match ? '> ' : ''}
<Link to={to}>
{children}
</Link>
</div>
)} />
);
}
We can use useRouteMatch and tell it what we want to match for, we can pass it an object with a path prop and an exact prop.
import { useRouteMatch } from 'react-router-dom';
function CustomLink({ children, to, exact }) {
const match = useRouteMatch({
exact,
path: to,
});
return (
<div className={match ? 'active' : ''}>
{match ? '> ' : ''}
<Link to={to}>
{children}
</Link>
</div>
);
}