Problem: isActive
(add active class to link) is not working.
My NavLink component is not working. I posted this problem several times in stack overflow no one solved my problem instead of solving they are tagging another question which doesn't solve my problem.
This is the home component:
import React from 'react';
// import Nav from './navbar';
import { NavLink } from "react-router-dom";
import "../App.css";
export default function home() {
return (
<div>
<NavLink
to="/"
style={isActive => ({
color: isActive ? "green" : "blue"
})}
>
home
</NavLink>
<NavLink
to="/about"
style={isActive => ({
color: isActive ? "green" : "blue"
})}
>
about
</NavLink>
<h1>Home page Here</h1>
</div>
)
}
This is the "About" component:
import React from 'react';
// import Nav from './navbar';
import { NavLink } from 'react-router-dom';
import "../App.css";
export default function about() {
return (
<>
<NavLink
to="/"
style={isActive => ({
color: isActive ? "green" : "blue",
backgroundColor: isActive ? "red" : "white"
})}
>
home
</NavLink>
<NavLink
to="/about"
style={isActive => ({
color: isActive ? "green" : "blue",
backgroundColor: isActive ? "red" : "white"
})}
>
about
</NavLink>
<h1>About page here</h1>
</>
)
}
I tried so many times and so many ways but the result is always same shown in above picture. I want isActive
feature to work fine and should add active class when I click on about or anything else in navbar
CodePudding user response:
That callback receives object not boolean i.e { 'isActive': boolean }
.
so it should be
style={(data) => ({
color: data.isActive ? "green" : "blue",
//...
})}
same as
style={({isActive}) => ({
color: isActive ? "green" : "blue",
//..
})}
CodePudding user response:
isActive is an object so you have to destructure it like {isActive}
. You have to use the end
prop, it will ensure the component isn't matched as "active" when its descendant paths are matched.
<NavLink
to="/"
end
style={({ isActive }) => ({ color: isActive ? "green" : "blue" })}
>
Home
</NavLink>
<NavLink
to="about"
style={({ isActive }) => ({ color: isActive ? "green" : "blue" })}
>
About
</NavLink>
Here is the working codesandbox link : https://codesandbox.io/s/quiet-morning-yk78xv?file=/src/App.js