Search code examples
javascriptreactjssidebar

React Newbie Question - How do I make a parameter true depending on the path?


I have a parameter called 'selected' that highlights the button on the sidebar in css. The tutorial I followed unfortunately didn't show how to change the state of this parameter to either true or false. I'd like to know how to do this for future projects.

import { Update } from '@mui/icons-material';
import React from 'react'
import { Link } from 'react-router-dom';
import './SidebarRow.css'

function SidebarRow({ selected, title, Icon, linkto }) {
    
    if (title == "Home" && (window.location.pathname == "/"))
    {
        selected = true;
    }
    else if (title == "Trending" && (window.location.pathname == "/trending"))
    {
        selected = true;
    }
    else{
        selected=false;
    }


    return (
        <Link to={`/${linkto}`} >
        <div className= {`sidebarRow ${selected && "selected"}`} >
            <Icon className="sidebarRow_icon"/>
            <h2 className="sidebarRow_title">{title}</h2>
            
        </div>
        </Link>
    )
}

export default SidebarRow;

The 'if' statements are my beginner take on this problem, and it doesn't work correctly. Any help would be much appreciated.


Solution

  • My recommendation is to use React Router V6 and <NavLink> as a special version of the <Link> that will add styling attributes to the rendered element when it matches the current URL.

    A <NavLink> is a special kind of <Link> that knows whether or not it is "active".

    https://reactrouter.com/docs/en/v6/api#navlink