Nivethan
Nivethan

Reputation: 3639

add style to navigation menu only to a active page is not working as expected in react router v6

i need to activate the current page with some styling for better user experience. first image is what i have done so far. i have a Parent component called < Dashboard /> inside of it i used < Outlet /> in order to render these 3 nested child components.

desired output


but the issue is that first link is always active no matter which link i click. is there any way to open the first tab by default and only add the styles when it's active using react router v6 or in any other way? thank you in advance for any help :)

my issue

this is my main route code on app.tsx

<Route path="dashboard" element={<Dashboard />}>
      <Route index element={<Productivity />} />
      <Route path="incentives" element={<Incentives />} />
      <Route path="development" element={<Development />} />
</Route>

this is my TabLink component

const TabLink:React.FC<Props> = (props) => {
const { link, label } = props;
return (
 <NavLink
  to={link}
  className={
  ({ isActive }) => (isActive
    ? 'text-cyan-400 border-b-4 border-current'
    : '')
  }
>
  <h6 className="hover:border-b-4 h-10 px-6 border-current hover:text-cyan-300">
    {label}
  </h6>
</NavLink>
);
};

Upvotes: 0

Views: 1349

Answers (2)

Nivethan
Nivethan

Reputation: 3639

after reading the docs properly for some time i figured out by adding end prop to the NavLink will easily resolve this issue!

this end prop will ensure this component isn't matched as "active" when its descendant paths are matched.

const TabLink:React.FC<Props> = (props) => {
const { link, label } = props;
return (
 <NavLink
  end
  to={link}
  className={
  ({ isActive }) => (isActive
    ? 'text-cyan-400 border-b-4 border-current'
    : '')
  }
>
  <h6 className="hover:border-b-4 h-10 px-6 border-current hover:text-cyan-300">
    {label}
  </h6>
</NavLink>
);
};

Upvotes: 1

Sangeet Agarwal
Sangeet Agarwal

Reputation: 1825

Here's how I solved this issue w/react router v6

look for aria-current

&[aria-current] {
 // apply css
}

or, look for the existence of active class

&[class*="active"] {
 // apply css
}

Upvotes: 0

Related Questions