Home > other >  React NavLink change sub element according to isActive
React NavLink change sub element according to isActive

Time:12-31

I have the following link:

<NavLink to={x.url} className={(x) = x.isActive ? 'active' : 'not-active' } >
    <img src={`icon-default.svg`} /> // change from default.svg to active.svg       
    Link Text
</NavLink>

I have my icons inside the HTML and not the CSS, I want to call a different img according to isActive, is it possible to do it on a sub element (the img tag)?

react-router-dom": "^6.0.2"

Thanks

CodePudding user response:

In react-router-dom v6 the children prop of the NavLink also takes a function that is passed an isActive prop. The function must return a ReactNode (i.e. JSX).

NavLink v6

declare function NavLink(
  props: NavLinkProps
): React.ReactElement;

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);
}

Use a render function on the children prop to render the link content and conditionally set the image source attribute.

<NavLink
  to={x.url}
  className={({ isActive }) = isActive ? 'active' : 'not-active'}
  children={({ isActive }) => {
    const file = isActive ? "active" : "default";
    return (
      <>
        <img src={`icon-${file}.svg`} />
        {x.text}
      </>
    );
  }}
/>
  • Related