I have a problem using MUI with react-router-dom v6.
import ListItem from '@mui/material/ListItem';
import { NavLink } from 'react-router-dom';
<List key={index}>
<ListItem
component={NavLink}
sx={{
color: '#8C8C8C',
}}
to={'/home'}
className={({ isActive }) => (isActive ? classes.activeLink : undefined)
>
<ListItemIcon></ListItemIcon>
<ListItemText primary='Home'/>
</ListItem>
</List>
className
not working and show error:
No overload matches this call.
The last overload gave the following error.
Type '({ isActive }: { isActive: any; }) => boolean' is not assignable to type 'string'
The expected type comes from property 'className' which is declared here on type 'IntrinsicAttributes & { button?: false | undefined; } & ListItemBaseProps & { components?: { Root?: ElementType<any> | undefined; } | undefined; componentsProps?: { ...; } | undefined; } & CommonProps & Omit<...>'
Thanks all, and here is my solution
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import { Theme } from '@mui/material/styles';
import { createStyles, makeStyles } from '@mui/styles';
import React from 'react';
import { NavLink } from 'react-router-dom';
const MyNavLink = React.forwardRef<any, any>((props, ref) => (
<NavLink
ref={ref}
to={props.to}
className={({ isActive }) => `${props.className} ${isActive ? props.activeClassName : ''}`}
>
{props.children}
</NavLink>
));
const useStyles = makeStyles((theme: Theme) =>
createStyles({
activeLink: {
backgroundColor: '#19ABC0',
color: '#FFFFFF',
borderRadius: 8,
'& .MuiSvgIcon-root': {
color: '#FFFFFF',
stroke: '#FFFFFF',
fill: '#19ABC0',
},
},
})
);
function Sidebar() {
const classes = useStyles();
return (
<>
<List>
<ListItem
component={MyNavLink}
sx={{
color: '#8C8C8C',
}}
to={'/home'}
activeClassName={classes.activeLink}
>
<ListItemIcon sx={{ stroke: '#8C8C8C', fill: '#FFFFFF' }}></ListItemIcon>
<ListItemText primary={'Home'} />
</ListItem>
</List>
<List>
<ListItem
component={MyNavLink}
sx={{
color: '#8C8C8C',
}}
to={'/dashboard'}
activeClassName={classes.activeLink}
>
<ListItemIcon sx={{ stroke: '#8C8C8C', fill: '#FFFFFF' }}></ListItemIcon>
<ListItemText primary={'Dashboard'} />
</ListItem>
</List>
</>
);
}
className={({ isActive }) => `${props.className} ${isActive ? props.activeClassName : ''}`}
To use MUI's className and add NavLink's active class.