What is the best approach to modifying the color of a menu item in the sidebar upon clicking it using Material-UI in a React application?

I am a beginner with this framework and my goal is to change the color when clicking on a Menu Item in the Sidebar. For example, clicking on the table component should change the table name and icon to white color. Could someone please help me figure out how to achieve this color change on menu item click?

Below is the code snippet:

class Sidebar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedIndex: 0
    };
  }

  handleListItemClick = (event, index) => {
    this.setState({
      selectedIndex: index
    });
  };

  render() {
    const { className, classes, onSidebarOpen, ...rest } = this.props;
    return (
      <div className={classes.root}>
        <Drawer
          className={classes.drawer}
          variant="permanent"
          classes={{
            paper: classes.drawerPaper
          }}
        >
          <div className={classes.toolbar} />
          <List>
            {["table", "organisation"].map((item, index) => {
              const Icon = itemsConfig[item].icon;
              return (
                <ListItem
                  component={Link}
                  to={itemsConfig[item].link}
                  selected={index === this.state.selectedIndex}
                  onClick={event => this.handleListItemClick(event, index)}
                  button
                  key={item}
                >
                  <ListItemIcon>
                    <Icon />
                  </ListItemIcon>
                  <ListItemText primary={itemsConfig[item].text} />
                </ListItem>
              );
            })}
          </List>
        </Drawer>
      </div>
    );
  }
}

export default withStyles(styles)(Sidebar);

Answer №1

Upon clicking the tabs, the following actions are achieved:

  • The background changes to grey
  • The icon switches to white

https://i.sstatic.net/FMygE.gif


Implementing conditional styles based on the state of the selected index is recommended.

<ListItem
  ...
  style={
    selectedIndex === index ? { backgroundColor: "grey" } : {}
  }
>
  <ListItemIcon>
    <Icon
      style={selectedIndex === index ? { color: "white" } : {}}
    />
  </ListItemIcon>
  <ListItemText primary={itemsConfig[item].text} />
</ListItem>

https://codesandbox.io/s/gallant-kowalevski-gxwfx?fontsize=14&hidenavigation=1&theme=dark

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 create asynchronous code or functions without using Web APIs at all?

Even though JavaScript is single-threaded, I can't help but wonder about a function that takes an unusual amount of time without any involvement from web APIs like this: console.log("start") function banana() { let bananaCount = 10; while (b ...

Drop-down menu feature in Material UI CardHeader

I'm currently working on incorporating a FormControl, a Select component, and a MenuItem into the action property of the CardHeader IconButton. Here's how the code looks at the moment: Rendering: <CardHeader action={ <IconButton ...

Handling keypress events in jHtmlArea

Currently working on a text-to-symbol conversion tool as a non-profit project, I have encountered an issue: For the WYSIWYG editing of the text, I am in search of a sleek and compact wysiwyg editor (like jHtmlArea). Since this editor displays floating div ...

JavaScript file slicing leads to generating an empty blob

I am currently working on a web-based chunked file uploader. The file is opened using the <input type="file" id="fileSelector" /> element, and the following simplified code snippet is used: $('#fileSelector').on('change', functio ...

Exploring Angular 7: Understanding the HTML5 Fullscreen API and Overcoming Errors

I am currently using Angular 7 and I am trying to implement a fullscreen button in my app. I have utilized the HTML5 Fullscreen API and created two functions for this purpose: openfullscreen() { // Trigger fullscreen console.log('gg'); ...

The problem arises when using `$state.go` as it does not properly transfer the value to `$stateParams`

Within componentA, I am using an angular code: $state.go('home', {selectedFilter: "no_filter"}); In componentB, I have the following code: if ($stateParams.selectedFilter === 'no_filter') However, I am encountering an issue where $s ...

Filtering data within a specific date range on an HTML table using JavaScript

I am attempting to implement a date filtering feature on my HTML table. Users should be able to input two dates (From and To) and the data in the "Date Column" of the table will be filtered accordingly. The inputs on the page are: <input type="date" i ...

Having trouble with expressJs router.post() not functioning properly with multiple middleware, resulting in an [object Undefined] error

I have been working on developing a REST API for my users, utilizing express-validator for validation before adding the user to the database. However, I encountered an issue while chaining my middleware in the router.py file which resulted in the error Err ...

Issues with object changes not reflecting in Vue.js 2.0 component rendering

I am facing an issue where my object is not updating immediately after a click event. It appears that a manual refresh or clicking on another element is necessary for the changes to take effect. How can I ensure that the object updates without the need for ...

Checking for a particular element's existence in an array using jQuery

Is there a way to verify the presence of the var element in the array sites? var sites = array['test','about','try']; var element = 'other'; ...

Assign the link to the button target using Material-UI

I'm attempting to create a button on material-ui.com that, when clicked, opens an external link in a new self window. Any insights on how to achieve this? <Button size="small" color="primary" href="https://example.com/" target="self"> ...

Struggling to understand how to utilize Firebase for logging in with Github

On my homepage, there is a link that directs to the following: <a href="/login">Login with Github</a> Within my app.js file, I have the following code snippet: app.get('/login', function(req, res) { var ref = new Firebase(&ap ...

Having trouble retrieving the toDataURL data from a dynamically loaded image source on the canvas

Currently, I am working on a project that involves a ul containing li elements with images sourced locally from the "/images" folder in the main directory. <section class="main"> <ul id="st-stack" class="st-stack-raw"> ...

What is the process for incorporating JavaScript-generated coordination into an HTML form?

As a newcomer to Javascript, I am on a mission to integrate geo coordination directly into an HTML form input field. After learning from W3Schools how to generate user latitude and longitude Coordination, I am now eager to input them directly into an HTML ...

Display a jQuery loading window

Need help with displaying a loading div when making an ajax post request. I've tried the following code but it's not working. Can someone please assist in resolving this issue? $(document).ready(function() { $('a.pagerlink').click( ...

Discovering unmarked content using Jsoup

I have been struggling to find a solution to my problem, but so far I have not found any clear answers in my search results. I have spent a considerable amount of time trying different suggestions from various posts that seemed somewhat related. Now, let&a ...

The onclick event for a Bootstrap .btn-group checkbox functions correctly in JSFiddle, but encounters issues when tested

The toggle button group in the form below utilizes Bootstrap and checkboxes. I am looking to track click events on the checkbox inputs. <html> <head> <title>Example: Bootstrap toggle button group</title> <meta charset="UTF-8 ...

Guide to integrating the Duda White Label API with an HTML website

Currently, I am in the process of integrating the Duda White Label API into a .html page to ensure that it aligns with my custom CSS. To guide me through this task, I am referring to the instructions provided at: After inserting my API key, Password, and ...

What is the best way to pass an event to a JavaScript function using React?

const [location, setLocation] = useState(default); const handleChangesFunction = (event, data, setLocationFunction) => { const storedLocation = [...data]; storedLocation[event.target.dataset.id][event.target.name] = event.target.value; ...

Creating a reset or refresh button with JavaScript: Step-by-step guide

Can someone please help me figure out how to create a button that will refresh the page while also resetting all values to their default settings? ...