skip to Main Content

I’m currently working on a React project with TypeScript and using SCSS for styling. I’m trying to select and style the active NavLink element from react-router-dom but haven’t been successful. Below is the relevant code:

Menu Component (JSX):

const Menu: FC<MenuProps> = () => {
  return(
  <div className={styles.Menu}>
    <NavLink to={"/profile"} >
      <div className={styles.navItem}>
        <FaHouseUser />
        <p>Profile</p>
      </div>
    </NavLink>
    <hr />
    
    <NavLink to={"/favorites"} >
      <div className={styles.navItem}>
        <FaRegHeart />
        <p>Favorites</p>
      </div>
    </NavLink>
    <hr />

    <NavLink to={"/explore"} >
      <div className={styles.navItem}>
        <FaSearch />
        <p>Explore</p>
      </div>
    </NavLink>
    <hr />

    <NavLink to={"/home"} >
      <div className={styles.navItem}>
        <FaHome />
        <p>Home</p>
      </div>
    </NavLink>
  </div>
  )
}

SCSS Styling:

  & > a {
    width: 25%;
    height: 100%;

    & > .navItem {
      @extend %flexCol;
      align-items: center;
      justify-content: center;
      gap: 0.25em;

      & > svg {
        color: rgba($colorPrimary, 0.75);
        font-size: 1.5em;
      }

      & > p {
        color: rgba($colorPrimary, 1);
        font-size: 0.75em;
      }
    }
  }

I am using ReactJS with TypeScript and SCSS for styling. I haven’t been able to select the "active" NavLink element. There are no error messages or console logs related to this problem, and I have checked for potential interference from other dependencies in my project.

i see that class does displayed in the element from the devtools but still i cant style it…

How can I select and style the active NavLink element using React Router DOM and SCSS? Any guidance or suggestions would be greatly appreciated!

2

Answers


  1. I guess :global(a.active) {} will help you.

    Login or Signup to reply.
  2. If nothing else works, maybe you could try inline styling using router’s isActive? (I’m fairly new at React and I’ve never worked with Typescript or SCSS)

    <NavLink
      to="/profile"
      style={isActive => ({
        color: isActive ? "green" : "blue"
      })}
    ></NavLink>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search