BoyX
BoyX

Reputation: 51

How to make activeClass on NavLink - styled component

Hi everyone im in trouble with active Link, i use Styled Component. I want my link to be Red when i'm on active link but nothing work. I tried ActiveCLassName but this not work too.

can someone help me?

thanks a lot

const NavLink = styled(Link)`
display: flex;
justify-content: center;
align-items: center;
height: 100%;
padding: 0 10px;
list-style-type: none;
text-decoration: none;
color: black;
background-color: yellow;
border: 0.1px solid lightgrey;
`;

export default function Nav() {
  return (
<NavWrapper>
  <UlNav>
    <LiNav>
      <NavLink to="/Burgers">Burgers</NavLink>
    </LiNav>
    <LiNav>
      <NavLink to="/Burgers">Pizza</NavLink>
    </LiNav>
    <LiNav>
      <NavLink to="/Burgers">Drinks</NavLink>
    </LiNav>
  </UlNav>
</NavWrapper>
)};

Upvotes: 5

Views: 2890

Answers (2)

Drew Reese
Drew Reese

Reputation: 202608

Issues

The issue I see is you are styling the Link component instead of the NavLink component. The Link component doesn't take any additional props for handling active links.

Solution

The NavLink component uses a .active class by default, so of you don't need any special classname you should use this class.

Example:

import { NavLink as BaseNavLink } from "react-router-dom";

const NavLink = styled(BaseNavLink)`
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 0 10px;
  list-style-type: none;
  text-decoration: none;
  color: black;
  background-color: yellow;
  border: 0.1px solid lightgrey;

  &.active {
    .... your active CSS rules here
  }
`;

Tested and works in both RRDv5 and RRDv6.

RRDv5 RRDv6
Edit how-to-make-activeclass-on-navlink-styled-component Edit how-to-make-activeclass-on-navlink-styled-component (forked)
"/drinks" "/burgers"
enter image description here enter image description here

Upvotes: 6

Evadin
Evadin

Reputation: 41

Your code is missing some stuff, like I am not seeing anywhere you are setting color: red like you want. Basically, the active link will have the class active applied, so either using a normal stylesheet or inside your styled(Link, you have to write a rule for that class that does what you want.

Like it says here Use 'active' state from React Router in Styled Components. You may have to use the &.active selector to apply the styles.

activeClassName just changes what the class name is, which isn't what you want. By default it is active which is fine, you just have to write the CSS rule to match it. https://v5.reactrouter.com/web/api/NavLink/activeclassname-string

Upvotes: 0

Related Questions