Search code examples
reactjssasssass-loader

a.active class works when importing x.scss file but not work using x.module.scss


I have a sidebar menu and I want to set active class when a Navlink clicked. it works when I import my scss class in tsx file :

//navigationItem.tsx
import "./NavigationItem.scss"

const navigationItem = (props: {
  active?: Boolean
  link: string
  icon: string
  children: any
}) => (
  <li className="NavigationItem">
    <NavLink to={props.link} className={props.active ? "active" : " "}>
      <i className={props.icon } aria-hidden="true"></i>
      <span className="spanStyle">{props.children}</span>
    </NavLink>
  </li>
)

//navigationItem.css
.NavigationItem a:hover,
.NavigationItem a:active,
.NavigationItem a.active {
  border-bottom: 4px solid colors.$primarymain;
  border-radius: 30px 0 0 30px;
}

but when I changed the file name to NavigationItem.module.scss and changed my tsx file like below, the Navlink will get the hover style but it do not keep this style as an active item. the class just works when the mouse is over it.

 import classes from "./NavigationItem.module.scss"
 const navigationItem = (props: {
 active?: Boolean
 link: string
 icon: string
 children: any
}) => (
  <li className={classes.NavigationItem}>
    <NavLink to={props.link} className={props.active ? {classes.active} : " "}>
      <i className={props.icon} aria-hidden="true"></i>
      <span className={classes.spanStyle}>{props.children}</span>
    </NavLink>
  </li>
)

Solution

  • It seems that I should use a different syntax in NavigationItem.module.scss, I just remove className={props.active ? "active" : " "} from tsx file and changed the scss file like this, see the way that I write a[class="active"] :

    .NavigationItem a:hover,
    .NavigationItem a:active,
    .NavigationItem a[class="active"] {
      background-color: colors.$lightgrey;
      border-bottom: 4px solid colors.$primarymain;
      border-radius: 30px 0 0 30px;
    }  
    

    I solve it using the issue React CSS Modules - Some CSS is not applied (for 'active' class set by NavLink component)