Search code examples
reactjsreact-hookssidebar

How can change the state of my link on click only if it’s not active already?


I have a sidebar with 2 links. I want when I press each one of them to get the active class so I can change the style of the active link, for example the Color of the text becomes blue, but my problem is that if I already am at the the first link and I click it again the state changes and so my style changes again without me changing the page. So if I am at the first link for example and I press it again, the active state goes on the second link while I still stay on the page of the first link.

Here is my code cause I can’t explain it really good :


const [active, setActive] = useState(false);

const setSideBar = () => setActive(!active);

return (
<Box className='menuWrapper'>

<Link to={PageRoutes.CHAPTER_ONE}>
<Box sx={{ display: 'flex' }}>
<Box
></Box>
<Box
onClick={setSideBar}
className={active ? 'menuItem' : ' menuItem active'}
>
<Box marginLeft='12px'>
<SideBarLineSvg />
</Box>
<span>CHAPTER ONE</span>
<h3>Control Programme</h3>
</Box>
</Box>
</Link>
<Link to={PageRoutes.CHAPTER_TWO}>
<Box sx={{ display: 'flex' }}>
<Box
></Box>
<Box
onClick={setSideBar}
className={active ? ' menuItem active' : 'menuItem'}
>
<Box marginLeft='12px'>
<SideBarLineSvg />
</Box>

<span>CHAPTER TWO</span>
<h3>National Programme</h3>
</Box>
</Box>
</Link>
</Box>
);
};

export default Menu;

In tried with if statement, but I guess I do something wrong because it doesn’t work at all when I add it


Solution

  •   const [active, setActive] = useState(false);
        
        const setSideBar = (key) => {
        if(active && key===1){
        setActive(!active);
        }
        if(!active && key===2)
        setActive(!active);
        }
        }
        
        return (
        <Box className='menuWrapper'>
        
        <Link to={PageRoutes.CHAPTER_ONE}>
        <Box sx={{ display: 'flex' }}>
        <Box
        ></Box>
        <Box
        onClick={()=>setSideBar(1)}
        className={active ? 'menuItem' : ' menuItem active'}
        >
        <Box marginLeft='12px'>
        <SideBarLineSvg />
        </Box>
        <span>CHAPTER ONE</span>
        <h3>Control Programme</h3>
        </Box>
        </Box>
        </Link>
        <Link to={PageRoutes.CHAPTER_TWO}>
        <Box sx={{ display: 'flex' }}>
        <Box
        ></Box>
        <Box
        onClick={()=>setSideBar(2)}
        className={active ? ' menuItem active' : 'menuItem'}
        >
        <Box marginLeft='12px'>
        <SideBarLineSvg />
        </Box>
        
        <span>CHAPTER TWO</span>
        <h3>National Programme</h3>
        </Box>
        </Box>
        </Link>
        </Box>
        );
        };
        
        export default Menu;
    

    send key value on onClickFn and do a execution as per key