Tengo una pregunta sobre el estilo de un componente de anclaje cuando está en la página activa.
Aquí está mi código:
import Link from 'next/link'; import styled from 'styled-components'; const NavStyle = styled.nav` display: flex; justify-content: space-between; .nav-link a { text-decoration: none; color: white; padding: 10px; background-color: #FFCF00; } `; export default function Nav() { return ( <NavStyle> <div className="nav-link"> <Link href="/" passHref> <a>HOME</a> </Link> <Link href="/pricing"> <a>PRICING</a> </Link> <Link href="/terms"> <a>TERMS</a> </Link> <Link href="/login"> <a>LOGIN</a> </Link> </div> <Link href="/"> <a>LOGO</a> </Link> </NavStyle> ) }Lo que quiero es que, cuando haga clic en el enlace y pase a otra página, el enlace activo (que coincide con la URL) tenga un fondo verde. He intentado esto, pero no hace ningún cambio:
const NavStyle = styled.nav` display: flex; justify-content: space-between; .nav-link a { text-decoration: none; color: white; padding: 10px; background-color: #FFCF00; &[aria-current] { background-color: green; } } `;Next.js no agregará aria-current a su enlace activo; sin embargo, puede crear un componente de Link personalizado que verifique si el nombre de pathname actual es el mismo que el accesorio href .
import React from "react"; import Link from "next/link"; import { useRouter } from "next/router"; const NavLink = ({ children, href }) => { const child = React.Children.only(children); const router = useRouter(); return ( <Link href={href}> {React.cloneElement(child, { "aria-current": router.pathname === href ? "page" : null })} </Link> ); }; export default NavLink; Luego, puede usar este componente en lugar del Link predeterminado siempre que desee agregar aria-current al enlace activo:
const NavStyle = styled.nav` display: flex; justify-content: space-between; a { background-color: #353637; color: #fff; padding: 1rem; text-decoration: none; &[aria-current] { background-color: #faf9f4; color: #353637; } } `; export default function Nav() { return ( <NavStyle> <div className="nav-link"> <NavLink href="/"> <a>HOME</a> </NavLink> <NavLink href="/pricing"> <a>PRICING</a> </NavLink> <NavLink href="/terms"> <a>TERMS</a> </NavLink> <NavLink href="/login"> <a>LOGIN</a> </NavLink> </div> <Link href="/"> <a>LOGO</a> </Link> </NavStyle> ); }