React Router v6 useNavigate with MUI Drawer

Viewed 1828

I'm using stackblitz trying to implement MUI Drawer and react-router-dom before I use it in an application. I don't think I am using the useNavigate hook correctly? any help would be muchly appreciated

Drawer.js

const Drawer = () => {
const classes = useStyles();
let navigate = useNavigate();

const itemsList = [
{
  text: 'Home',
  icon: <InboxIcon />,
  onClick: () => navigate('/home'),
},
{
  text: 'About',
  icon: <MailIcon />,
},
{
  text: 'Contact',
  icon: <MailIcon />,
},
];
return (
<MUIDrawer variant="permanent" className={classes.drawer}>
  <List>
    {itemsList.map((item, index) => {
      const { text, icon, onClick } = item;
      return (
        <ListItem button key={text} onClick={onClick}>
          {icon && <ListItemIcon>{icon}</ListItemIcon>}
          <ListItemText primary={text} />
        </ListItem>
      );
    })}
  </List>
</MUIDrawer>
);
};
export default Drawer;

App.js

const App = () => {
const classes = useStyles()
return (
<div className={classes.container}>
  <Drawer />
  <Router>
    <Routes>
      <Route path="/" exact element={<Home />} />
      <Route path="/contact" element={<Contact />} />
      <Route path="/about" element={<About />} />
    </Routes>
  </Router>
</div>
);
};
1 Answers

The error was caused from have the Drawer outside of the Router in App.js. I also made a user error when I copied the useStyles which I should of included in my original post.

App.js

const useStyles = makeStyles({
container: {
display: 'flex',
},
});
const App = () => {
const classes = useStyles();
return (
<div className={classes.container}>
  <Router>
  <Drawer />
    <Routes>
      <Route path="/home" exact element={<Home />} />
      <Route path="/about" element={<About />} />
      <Route path="/contact" element={<Contact />} />
    </Routes>
  </Router>
</div>
);
    };

Drawer.js

const useStyles = makeStyles({
drawer: {
width: '190px',
},
});

const Drawer = () => {
const classes = useStyles();
let navigate = useNavigate();

const itemsList = [
{
  text: 'Home',
  icon: <InboxIcon />,
  onClick: () => navigate('/home'),
},
{
  text: 'About',
  icon: <MailIcon />,
  onClick: () => navigate('/about'),
},
{
  text: 'Contact',
  icon: <MailIcon />,
  onClick: () => navigate('/contact'),
},
];
return (
<MUIDrawer variant="permanent" className={classes.drawer}>
  <List>
    {itemsList.map((item, index) => {
      const { text, icon, onClick } = item;
      return (
        <ListItem button key={text} onClick={onClick}>
          {icon && <ListItemIcon>{icon}</ListItemIcon>}
          <ListItemText primary={text} />
        </ListItem>
      );
    })}
  </List>
</MUIDrawer>
);
};

export default Drawer;
Related