Handling ActiveClassName with React Router
The activeClassName
property is used to give a CSS class to an element when it is active. The default given class is active. This will be joined with the className prop, see NavLink Docs. A simple implementation would look like this:
import { NavLink } from 'react-router-dom';
// ... some other code
<NavLink to="/" activeClassName="selected">
Home
</NavLink>
<NavLink to="/blog" activeClassName="selected">
Blog
</NavLink>
<NavLink to="/about" activeClassName="selected">
About
</NavLink>
A different style can be applied on the navigation link with the selected
CSS class.
.selected {
color: #ff0000; // red
}
Another option to the style the active route would be to use the activeStyle
property on NavLink
. It applies the styles when NavLink is active, see example below:
<NavLink
to="/faq"
activeStyle={{
fontWeight: 'bold',
color: #ff0000, // red
}}
>
FAQs
</NavLink>
💰: Start your cloud journey with $100 in free credits with DigitalOcean!
Styled Components Approach
Styled components are visual primitives to style your React App, see github.
To use the activeClassName
property from react-router
you have three options:
- Styled Components attrs method
- Passing activeClassName as styled component prop
- Using activeStyle from react-router
.attrs Method
The .attrs
method is a chainable method that attaches some props to a styled component. The first and only argument is an object that will be merged into the rest of the component's props. The attrs object accepts the following values:
export const StyledNavLink = styled(NavLink).attrs({
activeClassName,
})`
&.${activeClassName} {
color: red;
}
`;
<StyledNavLink activeClassName="any" />;
Passing activeClassName property
A Styled Component
passes all HTML attributes if it is a simple element, like a div or button or ..., and all props if it is a React Component.
To get the activeClassName pass it as a prop and get it in the styled component and apply the conditional styles.
export const StyledLink = styled(NavLink)`
color: blue;
&.${props => props.activeClassName} {
color: red;
}
`;
<StyledLink activeClassName="any" />;
Using activeStyle
react-router
has the activeStyle
prop for styling active links.
const StyledActiveLink = styled(NavLink)`
color: blue;
`;
<StyledActiveLink
activeStyle={{
color: 'red',
}}
></StyledActiveLink>;
TL;DR
There are three options to use the activeClassName in your styled components.
- attrs method
- Passing activeClassName as prop
- Using activeStyle
Thanks for reading and if you have any questions , use the comment function or send me a message @mariokandut. If you want to know more about React, have a look at these React Tutorials.
References (and Big thanks):
Top comments (1)
Easy and useful thank you