So, here is what exactly I am trying to do...
I am sending the class name and id using props.
and by checking the condition the particular style will be implemented to it.
(this code is used to implement Navigation bar)
so that my active class (Menu Tab) will be highlighted only.
but, when I used this it will highlight all navigation tabs at the same time.
export default function NavElements(props) {
const history = useLocation();
// console.log(history);
const [isActive, setIsActive] = useState(props.isActive);
useEffect(() => {
setIsActive(props.isActive);
},[props.isActive]);
function handleClick() {
props.onClick(props.index);
}
return (
<Link to={`${props.to}`}>
<div id={`${props.rectangle}`} onClick={handleClick} className={ isActive ? 'backgroundSelected' : ''}>
<div className="buttons-style" id={`${props.myClassName}`}>
<div className="text-align">
<div className="text-link">{props.Title}</div>
</div>
</div>
</div>
</Link>
)
}
You can also use useLocation as you defined also
export default function NavElements(props) {
let location = useLocation();
// console.log(history);
return (
<Link to={`${props.to}` className={`${location.pathname === props.to }? "active":""`}}>
<div id={`${props.rectangle}`}>
<div className="buttons-style" id={`${props.myClassName}`}>
<div className="text-align">
<div className="text-link">{props.Title}</div>
</div>
</div>
</div>
</Link>
)
}
The Logic is whenver the pathname equals to the endpoint directed by any <Link> , it gets active.
You can define your own class inplace of
activeclass of if you want
I'm a little bit confused about what you are trying to do. But if you want highlight the active menu, why can't you use NavLink instead of Link?. The NavLink has a property isActive which return true if the menu is active.