I have icon
inside Link
tag in my React component. I would like when Link is active to change the color of icon also. According to the code written below, when the link is active, the color of the icon also changes. But when I set the color of the icon in its css, the color of the icon no longer changes when the link is active. How would I change that?
const prop = ({ path, icon, isActive }) => (
<Link to={path} className={`nav-link ${isActive ? "active-link" : ""}`}>
<i className={`${icon} customIcon `}></i>
<span>{text}</span>
</Link>
)
This is css code:
.nav-link {
display: flex;
flex-direction: row;
align-items: center;
width: 100%;
padding-top: 8px;
padding-bottom: 8px;
font-family: "Roboto";
font-style: normal;
font-weight: 700;
font-size: 14px;
letter-spacing: 0.5px;
color: #52575c;
}
.customIcon {
width: 18px;
padding-right: 10px;
padding-left: 6px;
/* color: #52575c; */
}
.active-link {
color: #336cfb;
}
CodePudding user response:
There's a number of ways to approach this, one method I would try is nesting the color of the icon underneath the nav-link like this:
.nav-link.active-link {
color: #000; /* color when the nav-link is active */
}
.nav-link.active-link i {
color: #000; /* color of the icon when the parent nav-link is active */
}
Worst case, if you can't figure out another way to do this, you can override CSS specificity using the !important
operator like this:
color: #000 !important; /* value that should really be set */
CodePudding user response:
you can have class for your color and use it like this
const prop = ({ path, icon, isActive }) => (
<Link to={path} className={`nav-link ${isActive ? "active-link" : "not-active"}`}>
<i className={`${icon} customIcon `}></i>
<span>{text}</span>
</Link>
)
CSS
.active-link {
color: #336cfb;
}
.not-active {
color: #52575c;
}
remove the color property on .nav-link
class
you can use NavLink instead of the link, which gives you a callback function on the className prop that you can access the activity of link like this
<NavLink
to="/"
className={(link) => (link.isActive ? "active-nav-link" : "")
}
link
</NavLink>
CodePudding user response:
In the Icon className ${icon} is applying the color, adding a new line for customIcon classname with the active-link class prefix should work.
.nav-link {
....
}
.customIcon {
...
}
.active-link,
.active-link .customIcon {
color: #336cfb;
}
Keep the current className order ${icon} customIcon