48
loading...
This website collects cookies to deliver better user experience
:active
state.<Link>
component doesn't know what the current route is, so it can never hold an active state.next/router
to solve this problem and that is how I made the links below.<Link>
component from Nextjs by itself to add active styling. Therefore, you need to use the useRouter
hook which is part of the next/router
component. The useRouter
hook allows magically lets you access the router
object inside any component. This is how we are going to tell our application which page (route) the user is on, so we can then tell the link to apply active styles.<ActiveLink>
component, link the one below:import { useRouter } from "next/router";
import styled from "styled-components";
const StyledLink = styled.a`
color: ${({ href, path }) => (href === path ? "red" : "black"};
`;
function ActiveLink({ children, href }) {
const router = useRouter();
const handleClick = (e) => {
e.preventDefault();
router.push(href);
};
return (
<StyledLink href={href} onClick={handleClick} currentPath={router.asPath}>
{children}
</StyledLink>
);
}
export default ActiveLink;
<Link>
component because we use the push
method. This method handles the client-side transitions, meaning it is faster and doesn't trigger a full refresh. Which results in better performance and experience for the user. It also improves those tasty lighthouse scores.asPath
method. This method returns the path (or route) as shown in the browser address bar meaning we can conditionally check this against the href we pass as an argument to the <ActiveLink>
component.ActiveLink
component in other components when every you want to apply :active
styling.StyledLink
two key props. The first is the href
, the actual link we want next to route to. The second is currentPath
, which is the route that is currently in the browser.href
and the currentPath
components match using a ternary. If they match we apply the active styles in this case red
font otherwise we apply black
font.<Link>
component Flavio has some solutions here.