'List Item link using Material UI
I've created a Material UI ListItem menu as follows.
And when I click on the button, it updates the URL to http://localhost:3000/createIdea, but the page does not load via the router.
If you go into the browser URL window and hit Enter, then the page does load.
DrawerMenu.js has the routing:
<Route exact path='/createIdea' component={() => <CreateIdea />} />
And App.js -> drawerMenu.js* -> tiledata.js:
<ListItem button component={Link} to="/createIdea">
<ListItemIcon>
<WhatsHotIcon/>
</ListItemIcon>
<ListItemText primary="Create Idea"/>
</ListItem>
What can I do to fix this?
Solution 1:[1]
You can try this. It worked for me.
import { Link } from 'react-router-dom';
<ListItem button component={Link} to="/createIdea">
<ListItemIcon>
<WhatsHotIcon/>
</ListItemIcon>
<ListItemText primary="Create Idea"/>
</ListItem>
Solution 2:[2]
As of react-router-dom 5.2.0; @material-ui/core 4.11.0;
import { useHistory } from 'react-router-dom';
const Foo = () => {
const history = useHistory();
return (
<ListItem onClick={() => history.push('/createIdea')}>
<ListItemIcon>
<WhatsHotIcon/>
</ListItemIcon>
<ListItemText primary="Create Idea"/>
</ListItem>
);
};
Solution 3:[3]
Try this
<List disablePadding>
<ListItem button component={Link} to="/">
<ListItemText>Home</ListItemText>
</ListItem>
<ListItem button component={Link} to="/about">
<ListItemText>About Me</ListItemText>
</ListItem>
</List>
Solution 4:[4]
Slightly different version for current MUI:
import { Link } from 'react-router-dom';
<ListItem key="someKey" disablePadding>
<ListItemButton component={Link} to="/index" >
....
</ListItemButton>
</ListItem>
Assuming then you have a Router like so:
import {
BrowserRouter as Router,
Routes,
Route,
} from "react-router-dom";
const App = () => {
return (
<React.Fragment>
<Router>
<Routes>
<Route path="/index" element={<YourIndexComponent />} />
</Routes>
</Router>
</React.Fragment>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zahirul Haque |
| Solution 2 | Dharman |
| Solution 3 | Sjonchhe |
| Solution 4 | Rafael |
