Search code examples
javascriptreactjsmaterial-uifrontendmern

How to navigate on different componet using material ui


How to navigate on a different component using material UI

here is the code of my drawer list

  <List>
          {['POS', 'Stock', 'Send email', 'Drafts'].map((text, index) => (
            <ListItem button key={text}>
              <ListItemIcon>
                {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
              </ListItemIcon>
              <ListItemText primary={text} />
            </ListItem>
          ))}
    </List>

I would like to navigate on the stock page

App.js

  <Provider store={store}>
    <BrowserRouter>
        < Routes>
          <Route exact path='/' element={<Login/>} />
          <Route exact path='/dashboard' element={<Dashboard/>} />
          <Route exact path='/product' element={<Product/>}/>
        </Routes>
      </BrowserRouter>
    </Provider>

I want that if I will click this listItem element so that component will open here is my GUI

enter image description here


Solution

  • There are two ways to handle routing in this case:

    1. <Link to="<route>"> provided by react-router itself. You can wrap your ListItem with it and it will work as an anchor tag and redirect to the page. Ref
    2. You can also handle it by adding an onClick method to ListItem and passing the route you want to redirect to. Using the useHistory hook, the history object can be instantiated and the method history.push(<route>) will do the job. Ref