5

Could you please help me to understand why active style is all the time active? I've got "react-router-dom": "^6.1.1". I tried different variety of way to apply this stylies the way it's written in react router documentation, but still i can't find the mistake why it is so.

import { NavLink } from "react-router-dom";
import s from "../Sidebar/Sidebar.module.css";

function Sidebar() {
  return (
    <div className={s.Sidebar}>
      <NavLink
        to="/profile"
        style={(isActive) => ({ color: isActive ? "green" : "blue" })}
        className={s.navItems}
      >
        Profile
      </NavLink>
      <NavLink
        to="/messages"
        style={(isActive) => ({ color: isActive ? "green" : "blue" })}
        className={s.navItems}
      >
        Messages
      </NavLink>
      <br />
    </div>
  );
}

export default Sidebar;
.navItems{
  display: flex;
  text-decoration: none;
  font-size: 26px;
  padding-bottom: 8px;
}

  [1]: https://i.stack.imgur.com/cCsBw.png
Elizabeth
  • 1,271
  • 2
  • 5
  • 11

2 Answers2

8

In react-router-dom v6 the isActive is a prop value destructured from a function passed to either of the children, className, and style NavLink props.

NavLink

interface NavLinkProps
  extends Omit<
    LinkProps,
    "className" | "style" | "children"
  > {
  caseSensitive?: boolean;
  children?:
    | React.ReactNode
    | ((props: { isActive: boolean }) => React.ReactNode);
  className?:
    | string
    | ((props: { isActive: boolean }) => string);
  end?: boolean;
  style?:
    | React.CSSProperties
    | ((props: {
        isActive: boolean;
      }) => React.CSSProperties);
}

Destructure isActive in your style callback, style={({ isActive }) => ({ color: isActive ? "green" : "blue" })}.

<NavLink
  to="/profile"
  style={({ isActive }) => ({ color: isActive ? "green" : "blue" })}
  className={s.navItems}
>
  Profile
</NavLink>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
0
this is worked for me
const match = useMatch(`${path}/*`);

Usage example:

interface NavbarItemProps {
  path: string;
  title: string;
  icon: OverridableComponent<SvgIconTypeMap> & { muiName: string };
  variant: GLOBAL.GlobalSlice['leftDrawerVariant'];
}

const NavbarItem = ({ path, icon: Icon, title, variant }: NavbarItemProps): ReactElement => {

  const match = useMatch(`${path}/*`);

  return (
    <LightTooltip
      disableHoverListener={variant === 'large'} 
      placement="right" 
      title={title}
    >
      <ListItemButton
        key={path}
        className={classNames({ 'bg-white text-brand fill-brand': match })}
        component={NavLink}
        to={path}
      >
        <ListItemText 
          className="whitespace-nowrap overflow-hidden" 
          primary={title} 
        />
      </ListItemButton>
    </LightTooltip>
  );
};