0

Here is my code:

import React from "react";
import "./sidebar.scss";
import HomeOutlinedIcon from "@material-ui/icons/HomeOutlined";
import InfoOutlinedIcon from "@material-ui/icons/InfoOutlined";
import ChatOutlinedIcon from "@material-ui/icons/ChatOutlined";
import LanguageIcon from "@material-ui/icons/Language";
import { NavLink } from "react-router-dom";


<div className="sidebar__Wrapper">
    <div className="iconsContainer">
        <div className="icons">
        <NavLink to="/">
            <HomeOutlinedIcon className="iconsDefaultStyle" />
        </NavLink>
        <NavLink to="/worldwide">
            <LanguageIcon className="iconsDefaultStyle" />
        </NavLink>
        <NavLink to="/importantinfo">
            <InfoOutlinedIcon
            className="iconsDefaultStyle"
            fontSize="default"
            />
        </NavLink>
        </div>
    </div>
</div>

I am using Material UI icons inside NavLink initially the color of the icon is gray but I want to change the color of Icon when the link is active, I mean What I want to do is:

When I click on the icon the color of the icon must be changed which will indicate that the current Link is active. I have done this by using separate state for every link which will change the classes when the particular icon is clicked but it makes my code very lengthy. Is there any other way to achieve this?

  • Could you share the imports that you are using? – Kenny John Jacob Aug 25 '20 at 07:32
  • 1
    You can keep an 'activeLink' state which changes based on the link selected. You can then just use a ternary to decide which class to show: className="{activeLink === "home" ? "yourActiveClass" : "iconsDefaultStyle". – Phobos Aug 25 '20 at 07:35
  • @KennyJohnJacob I edited teh post Now you can see Imports –  Aug 25 '20 at 07:43
  • @Phobos I understand what you are saying but for that I need to create more then 1 state,i mean I need sperate state for every Icon(Link). –  Aug 25 '20 at 07:46

1 Answers1

0

You can modify your code to have this format

import { Link, useLocation } from "react-router-dom";
import MenuItem from '@material-ui/core/MenuItem';

const { pathname } = useLocation();

<MenuItem className={pathname === "/worldwide" ? "active": "inactive"} 
  component={Link} to="/worldwide">
    <LanguageIcon className="iconsDefaultStyle" />
</MenuItem>

The idea is that you fetch the current pathname from react router, and for each link you will write a condition which becomes true if the pathname matches that route. (see original at https://stackoverflow.com/a/50614553/8323067)

Here you can set the className to the css class based on the same condition (as mentioned by @Phobos)

Kenny John Jacob
  • 1,188
  • 8
  • 21