Expanding Nested List Components in Material-UI using ReactJS by utilizing the URL structure

I'm currently working with ReactJS and Material-UI. Is there a way to have the MUI nested list display specific items based on the URL? For example, if a user is on /inbox/starred/, I want the Inbox item to be open and Starred to be highlighted. I attempted to use React Router Nested Routes but couldn't quite get it right.

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import ListSubheader from '@material-ui/core/ListSubheader';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Collapse from '@material-ui/core/Collapse';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import DraftsIcon from '@material-ui/icons/Drafts';
import SendIcon from '@material-ui/icons/Send';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import StarBorder from '@material-ui/icons/StarBorder';

const useStyles = makeStyles((theme) => ({
  root: {
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
  nested: {
    paddingLeft: theme.spacing(4),
  },
}));

export default function NestedList() {
  const classes = useStyles();
  const [open, setOpen] = React.useState(true);

  const handleClick = () => {
    setOpen(!open);
  };

  return (
    <List
      component="nav"
      aria-labelledby="nested-list-subheader"
      subheader={
        <ListSubheader component="div" id="nested-list-subheader">
          Nested List Items
        </ListSubheader>
      }
      className={classes.root}
    >
      <ListItem button>
        <ListItemIcon>
          <SendIcon />
        </ListItemIcon>
        <ListItemText primary="Sent mail" />
      </ListItem>
      <ListItem button>
        <ListItemIcon>
          <DraftsIcon />
        </ListItemIcon>
        <ListItemText primary="Drafts" />
      </ListItem>
      <ListItem button onClick={handleClick}>
        <ListItemIcon>
          <InboxIcon />
        </ListItemIcon>
        <ListItemText primary="Inbox" />
        {open ? <ExpandLess /> : <ExpandMore />}
      </ListItem>
      <Collapse in={open} timeout="auto" unmountOnExit>
        <List component="div" disablePadding>
          <ListItem button className={classes.nested}>
            <ListItemIcon>
              <StarBorder />
            </ListItemIcon>
            <ListItemText primary="Starred" />
          </ListItem>
        </List>
      </Collapse>
    </List>
  );
}

Answer №1

To tackle this assignment, my suggestion is to utilize the URL parameter feature of react-router.

Initially, you will have to modify your route to something similar to this structure:

<Route path="/:drawer/:subDrawer" children={<NestedList />} />

Note the presence of :drawer and :subDrawer variables in the aforementioned path. These will help us identify our current route.

Subsequently, within your component, access the values of drawer and subDrawer from the URL parameters as demonstrated below (certain details are omitted for clarity):

// ...other imports
import { useParams } from 'react-router-dom';

export default function NestedList() {
  const classes = useStyles();
  
  const { drawer, subDrawer } = useParams();
  
  return (
    <List>
      {//... other stuff}

      <ListItem button onClick={handleClick}>
        <ListItemIcon>
          <InboxIcon />
        </ListItemIcon>
        <ListItemText primary="Inbox" />
        {// modified logic here}
        {drawer === 'inbox' ? <ExpandLess /> : <ExpandMore />}
      </ListItem>
      <Collapse in={open} timeout="auto" unmountOnExit>
        <List component="div" disablePadding>
          {// modified logic here}
          <ListItem
            selected={subDrawer === 'starred'}
            button className={classes.nested}
          >
            <ListItemIcon>
              <StarBorder />
            </ListItemIcon>
            <ListItemText primary="Starred" />
          </ListItem>
        </List>
      </Collapse>
    </List>
  );
}
  

Given that we rely on the route to determine the open drawer, it is essential to update the onClick event for each menu item to redirect the user to the correct route. For instance, when a user selects Sent mail, they should be redirected to /sent-mail and the corresponding button for Sent mail would resemble this:

      <ListItem button selected={subDrawer === 'sent-item'}>
        <ListItemIcon>
          <SendIcon />
        </ListItemIcon>
        <ListItemText primary="Sent mail" />
      </ListItem>

and so forth...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the purpose of the component prop in a Grid layout?

I recently came across an example on material-ui's documentation that had a line of code I couldn't quite grasp. It was the component={Paper} part in this snippet: <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square> Wh ...

An issue arises when trying to import the modal popup

Hey there! I'm currently trying to implement a modal popup in react-bootstrap, but I keep running into an error that says "Props not defined". I followed the instructions from the react-bootstrap documentation, but I can't seem to figure out what ...

Crafting a custom look for your TextField with MaterialUI

I am currently utilizing styled components, which is working well for me. The only issue I am facing is that I want to style the border-radius of a specific TextField component. How can I achieve this? import React from 'react'; import TextFie ...

Utilizing Formik alongside Yup and React-select for enhanced validation

Currently, I am implementing form validation in a React project using both Yup and Formik. The challenge I am facing is with validating a react-select element within the form. To achieve this, I am utilizing the validationSchema property of Formik to valid ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Sending user input from search component to main App.js in React

I'm currently working on an app that searches a Movies database API. I have a main fetch function in App.js, and in tutorials, people are using a search bar within this main APP component. I'm wondering if it would be better to create a separate ...

Leveraging PapaParse for CSV file parsing in a React application with JavaScript

I am encountering an issue with reading a CSV file in the same directory as my React app using Javascript and Papaparse for parsing. Below is the code snippet: Papa.parse("./headlines.csv", { download: true, complete: function(results, f ...

Activate the useEffect function in react

I am retrieving data from a Firebase database and it works when the component initially renders. However, I am struggling to make it fetch again whenever there is a new entry in the database. Here is what I've attempted: I tried passing a state var ...

What is the best way to organize an Express application that handles both API requests and views?

Currently, I am in the process of developing a small application that will function as both a website and its API. To achieve this, I am utilizing Node, Express, and Webpack. The structure of my directory is organized as follows: >client |>dist ...

Begin with a blank canvas and wait for inspiration to shape your journey

Is there a similar feature in REACT to what Angular offers with nullable types? In Angular, you can use something like crawlList?.jobsList {crawlList.jobsList.map(crawl => ( <div>test</div> ))} The issue I'm facing is that I set jo ...

Unable to edit the current value of an input component in ReactJS

I need to implement a search feature for a list of items using ReactJS. You can view the project on JSBIN. The issue I am facing is that when I input 'mi' in the search box to filter by ID, the filtration works correctly but the input value does ...

Tips for styling buttons in react-admin with custom CSS

I need some help with customizing buttons in react-admin. I am new to the platform and unsure about how to go about changing the button CSS for various actions such as create, edit, and export. Can anyone provide guidance on the best way to customize these ...

Encountering a problem while trying to run the command `npm run build`, receiving an error stating `TypeError: MiniCssExtractPlugin is not a

I encountered an issue while working on my react app. It runs smoothly with npm start, but when I attempt to build the app, it throws an error message. PS D:\ ****\ **\*\profile> npm run build > <a href="/cdn-cgi/l/email-prote ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

ReactDOM fails to display the application, even after successfully compiling

I am facing an issue where the app is not rendering despite successful compilation with yarn run. Here is the code snippet: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import {Provider ...

What could be causing html-webpack-inline-source-plugin to prevent the page from refreshing after editing CSS files?

Currently, I am utilizing a plugin that embeds all CSS within the final HTML file. This method prevents the application from refreshing in development mode. Whenever I make edits to the CSS, the build process completes normally, but the styles do not updat ...

ReactStrap: Difficulty concealing navbar item based on screen dimensions

Currently, I am referring to the official documentation to implement a scenario where a NavItem is only displayed for screen sizes greater than sm. As per the guidelines provided in the documentation, I have included the following attributes: https://i ...

Front-end displaying empty data fields on my webpage

I've been struggling to understand why my data isn't mapping correctly on these two components. I have attempted two debugging methods to analyze my code and have observed the data object for both the navigation and footer. Unable to comprehend ...

I encountered a SyntaxError while parsing JSON due to an absence of a number after a minus sign at position 1

I am trying to use the replicate model visoar/product-photo:edf42659dae0da88a26dba4912e7e4bb6c2fba25b1e1c6a5464cf220e467bce0, but when I provide it with an image and a prompt like on this page.tsx: "use client" import { LandingNavBar } from &apo ...

Deployment to DigitalOcean fails due to GitHub action error

I'm encountering an issue during the deployment process to DigitalOcean via github actions and I can't figure out why it's throwing an error related to python. Could this be a result of the docker images I'm utilizing? Despite my attemp ...