Issue
I intend to style the active route in React using react-router. I am using NavLink to do so. Please see the below code:
COMPONENT.JS
import React from 'react';
import classes from './navBar.module.css';
import {NavLink} from 'react-router-dom'
const NavBar = (props) => {
return (
<div className={classes.navBarStyle}>
<p className={classes.navBarTitle}>EMPOYEE DATABASE</p>
<nav className={classes.nav}>
<ul className = {classes.navUl}>
<li><NavLink to="/" exact>HOME</NavLink></li>
<li><NavLink to="/addEmployee">ADD</NavLink></li>
</ul>
</nav>
</div>
)
}
export default NavBar;
COMPONENT.module.css
.nav {
height: 100%;
}
.navUl {
list-style-type: none;
margin: 0;
padding: 0;
height: 100%;
display: flex;
}
.navUl li {
height: 100%;
}
.navUl li a{
text-decoration: none;
color: inherit;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.navUl li a:hover{
background-color: rgb(235, 91, 25);
}
/* STYLING THE ACTIVE ROUTE HERE */
.navUl li a.active {
background-color: rgb(119, 47, 14);
border-bottom: 2px solid white;
}
I can see the class = "active"
getting embedded inside the anchor tag when a particular route is selected.
Hence I intend styled with a.active
, but it wasn't getting styled as specified in css file. I don't see any specifity issues in CSS and even the styles doesn't get appeared in the chrome developer tools. Irony is a:hover
is working but a.active
isn't. Where am I going wrong ?
Solution
you may use activeStyle
class in your <NavLink/>
Tag:-
import React from 'react';
import classes from './navBar.module.css';
import {NavLink} from 'react-router-dom'
const NavBar = (props) => {
const style = {
color: 'black',
fontWeight: 'bold'
}
return (
<div className={classes.navBarStyle}>
<p className={classes.navBarTitle}>EMPOYEE DATABASE</p>
<nav className={classes.nav}>
<ul className = {classes.navUl}>
<li><NavLink activeStyle={style} to="/" exact>HOME</NavLink>
</li>
<li><NavLink activeStyle={style} to="/addEmployee" >ADD</NavLink></li>
</ul>
</nav>
</div>
)
}
export default NavBar;
Answered By - Mehadi Hassan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.