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.
The main issue in your logic is that you are passing selected as a props but then want to change its value. A props should not be modified. Either define the proper value for selected in your parent component and pass it down to the child component, or create a new variable such as :
let localSelected = (title == "Home" && (window.location.pathname == "/") || (title == "Trending" && (window.location.pathname == "/trending") ? true : false ;
You can keep the if logic but ternary operator seems much cleaner.
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".
I would suggest you, apart from the previous answer, reading about NavLink component from React Router. I think most of the logic you need is included on it.