I am using React and Material UI to create a basic navbar setup, because React-Router-Dom does not want to work inside this project, and would be overkill for what I am doing. When I click the a button, it is setting the menuItems id as the value of the activeView. I am trying to conditionally change the className of the button to active (like this: className={classes.active} ), so I can access the Material UI styling class active. I tried a solution I found in another questions, but it does want to work for me. Can someone please tell me what I am doing wrong? Currently it does appear to be able to find the 'active' class, giving me this error "Cannot find name 'active'.ts(2304)". I even tried to create the className 2 different ways.
Material UI Class in NavBarStyling.tsx
nav: {
<--removed, not relevant-->
},
'& button.active': {
color: '#dadad8',
backgroundColor: 'blue',
},
},
active: {
color: '#dadad8',
backgroundColor: 'blue',
},
Setting state in main App
const [activeView, setActiveView] = React.useState(1);
Navbar.tsx
import { useNavStyles } from './NavBarStyling';
const classes = useNavStyles();
const NavBar = () => {
return(
<div className={classes.nav}>
{menuItems.map((menuItems: { id: number; label: string; }) => (
<Button key={menuItems.id} onClick={() => setActiveView(menuItems.id)}
className={classes[`${activeView === menuItems.id ? active : ''}`]}
>
{menuItems.label}
</Button>
))}
</div>
)
};
Here is your error className={classes[`${activeView === menuItems.id? active: ''}`]}
className={classes[`${activeView === menuItems.id? active: ''}`]}
You need to return active
as a string and not a variableclassName={classes[activeView===menuItems.id?'active':'']}
or like thisclassName={activeView===menuItems.id?classes.active:''}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.