There is this property, aria-current in a NavLink, it is set is set to value page (aria-current="page" for the selected element).
Is there a way to access it in React? In order to change the styling for the other links which aren't selected.
CodePudding user response:
Could this be done more easily with CSS?
.navLink:not([aria-current]) { color: red;}
CodePudding user response:
See below, this is what I do with styled components with react router v6. But you can follow the same way of doing things with any other styling strategy.
const StyledNavLink = styled(NavLink)`
text-decoration: ${(props) => {
console.log(props.style);
return props.style ? (isActive) => (isActive ? "underline" : "none") : "none";
}};
&:hover {
text-decoration: underline;
}
&[aria-current] {
color: red;
}
`;
Or, as shown below, one can check for existence of the active class
const StyledNavLink = styled(NavLink)`
text-decoration: ${(props) => {
console.log(props);
return props.style ? (isActive) => (isActive ? "underline" : "none") : "none";
}};
&:hover {
text-decoration: underline;
}
&[class*="active"] {
color: red;
}
`;
CodePudding user response:
Yup you can access it via a ref of the element. For example:
const navRef = useRef(null);
...
return <nav ref={navRef}>{navRef.current.ariaCurrent}</nav>
Just a heads up: Attributes that start with aria are only intended for accessibility purposes so I wouldn't rely on them for the styling of components.
CodePudding user response:
Yes, you can access it using useRef, and do whatever you want.
