Home > Software design >  How to apply a style to the active link of a NavLink element using mui styled()?
How to apply a style to the active link of a NavLink element using mui styled()?

Time:10-22

I have a NavLink wrapper component. I want to add an .active style to this component when it becomes active, but I don't know how it can be done with styled(). How can this be achieved?

Here is my code:

import { forwardRef } from "react";
import { NavLink as NavLinkBase } from "react-router-dom";
import { styled } from "@mui/system";


const NavLink = forwardRef((props, ref) => {
  return (
    <NavLinkBase   
      ref={ref}
      {...props}
      className={({ isActive }) => [
        props.className,
        isActive ? 'active' : null,
      ]
        .filter(Boolean)
        .join(" ")
      }
      end={props.to === '/' ? true : false}
    />  
  )
});

export default NavLink

CodePudding user response:

The NavLink component has an "active" classname by default when it is active. In the simplest terms you could do the following to define the CSS/styling.

const NavLink = styled(NavLinkBase)(({ theme }) => ({
  ... default styling ...

  "&.active": {
    ... active styling ...
  }
}));

If you are also wanting to define some default props, like the end prop logic, then create an anonymous function component.

const NavLink = styled(props => (
  <NavLinkBase {...props} /* set default props here */ />
))(({ theme }) => ({
  ... default styling ...

  "&.active": {
    ... active styling ...
  }
}));

Example:

const NavLink = styled((props) => (
  <NavLinkBase {...props} end={props.to === "/"} />
))(({ theme }) => ({
  textDecoration: "none",

  "&.active": {
    color: "green",
    fontSize: theme.spacing(3)
  }
}));

...

<ul>
  <li>
    <NavLink to="/">Home</NavLink>
  </li>
  <li>
    <NavLink to="/foo">Foo</NavLink>
  </li>
  <li>
    <NavLink to="/bar">Bar</NavLink>
  </li>
</ul>

Edit how-to-apply-a-style-to-the-active-link-of-a-navlink-element-using-mui-styled

enter image description here

  • Related