Modify the appearance of the element that is currently chosen

I have a navigation menu and I would like to change the style of the element that is selected from the list in the navigation menu. I am using React with the Grid element from material-ui.

NavigationMenu.tsx:

import React, { useState, useEffect } from "react";
import { Grid } from "@material-ui/core";
import './NavigationMenu.css';
import history from '../../history';

const NavigationMenu = () => {
    const [itemStyle, setItemStyle] = useState("nav-item");

    useEffect(() => {
        window.addEventListener('click', handleSelectedItem);
      });

    const handleSelectedItem = (event: any) => {
        setItemStyle("nav-item");
        event.target.classList.add("selected");
        const selectedItem = event.target.id;
        history.push('/GeneralPage/' + selectedItem);
    }

    return (
        <div className="navigation-menu">
            <Grid container direction="column" justify="center" alignItems="center" spacing={2}>
                <Grid item id="Books"
                 className={itemStyle}>
                    Books Management
                </Grid>
                <Grid item id="Authors"
                 className={itemStyle}>
                    Authors Management
                </Grid>
                <Grid item id="Users"
                 className={itemStyle}>
                    Users Management
                </Grid>
            </Grid>
        </div>
    );
}

export default NavigationMenu;

NavigationMenu.css:


.nav-item {
    cursor: pointer;
    text-align: center; 
    background-color: none;
    width: 100%;
}

.selected{
    background-color: hotpink;
}

I am looking to update the style of the selected element by applying the "selected" class. How can I achieve this?

Answer №1

Take a look at the following code snippet where a class is added to the selected item.

Demo https://codesandbox.io/s/bold-water-jmlch

import { Grid } from "@material-ui/core";
import "./Navigate.css";

const Navigate = () => {
  const [selectedItem, setSelectedItem] = useState("");

  const handleSelectedItem = event => {
    setSelectedItem(event.target.id);
  };

  return (
    <div className="navigate-comp">
      <Grid
        container
        direction="column"
        justify="center"
        alignItems="center"
        spacing={2}
      >
        <Grid
          item
          id="Books"
          onClick={handleSelectedItem}
          className={`nav-item ${selectedItem === "Books" ? "selected" : ""}`}
        >
          Books Management
        </Grid>
        <Grid
          item
          id="Authors"
          onClick={handleSelectedItem}
          className={`nav-item ${selectedItem === "Authors" ? "selected" : ""}`}
        >
          Authors Management
        </Grid>
        <Grid
          item
          id="Users"
          onClick={handleSelectedItem}
          className={`nav-item ${selectedItem === "Users" ? "selected" : ""}`}
        >
          Users Management
        </Grid>
      </Grid>
    </div>
  );
};

export default Navigate;

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

Dimming the background of my page as the Loader makes its grand entrance

Currently, I am in the process of developing a filtering system for my content. The setup involves displaying a loader in the center of the screen whenever a filter option is clicked, followed by sorting and displaying the results using JQuery. I have a v ...

Utilizing React and MobX to dynamically render components based on observable arrays

I'm currently facing a challenge with trying to map an array in order to display components for each entry. Here's my current approach: Here is the structure of my RankStore; const RankStore = observable({ loading: false, error: "", ra ...

I need to display a VARCHAR variable retrieved from PHP in a visually appealing way with HTML/CSS. What is the best way to automatically format it to prevent it from appearing as one long, uninterrupted sentence?

Is there a way to automatically format the text retrieved from a VARCHAR variable in a MySQL database via PHP so that it displays correctly with line breaks? Currently, when I display it on an HTML page, it appears as one long string. I've considered ...

Require users to sign in immediately upon landing on the homepage in Next JS version 13 or 14

I have created a traditional dashboard application using Next.js 13 with a pages router that places all pages behind the /dashboard route, such as /dashboard/users, /dashboard/orders, and so on. I want to ensure that when a user visits the website, a fork ...

Bootstrap 4.0. When it comes to buttons, they seem to have trouble cooperating with other DIV elements

Today is my first time seeking help on StackOverflow: I'm encountering an issue with my website where the floating arrow at the bottom of the page is obstructing my ability to click on buttons. Whether it's a Bootstrap button or HTML button, non ...

Align the emoji in the center of the absolute div horizontally

I'm currently working on a project involving placing emojis at different coordinates within a webpage. At times, the emoji is larger than its container. For instance, here is an example of HTML code that positions a house with a font size of 100px ins ...

attempting to eliminate on-screen buttons by hovering over the video

Is there a way to make my video play on loop like a GIF without the controls ever showing? I want it to have a seamless playback experience. Any ideas would be appreciated. P.s. Don't worry about any StackOverflow errors when running the snippet. Than ...

Issue with react-native: borderRadius not properly framing component dimensions

The issue with the borderRadius style attribute not displaying correctly on a component. Ideally, one would expect to see a green circle on the red background seamlessly without any white space. Unfortunately, this is what is currently being displayed: ...

Guide to displaying an OBJ file in a MUI component using three.js

Currently encountering an issue with displaying an OBJ file (or any 3D model) within the UI. The OBJ file loads perfectly fine, but the challenge lies in showcasing it inside the MUI component. Using three.js library for this functionality. Here's t ...

Guide on transforming MUI ReactJS datepicker to display dates in Arabic

I've been attempting to switch the language in the MUI datepicker to Arabic, but haven't had any success. I'm currently using '@mui/x-date-pickers' Trying to use either locale or localetext in LocalizationProvider results in an er ...

webpack is having trouble compiling TypeScript with React components

I've been working on setting up a TypeScript React project with webpack. I followed the TypeScript Tutorial, but I keep running into an error message that says `module parse failed: ... you may need an appropriate loader` Interestingly, I can success ...

Tips for emphasizing a row of various list boxes when hovering in asp.net

I am facing an issue with two listboxes on my website. Currently, I can only highlight one item at a time by mousing over the listbox. However, I would like to be able to highlight items in both listboxes simultaneously when I mouseover either listbox1 or ...

How to modify the background image of a div using CSS from a specific folder

<head id="Head1" runat="server"> <title>Title</title> <style> .parallax { /* The image used */ background-image: url(Pictures/BackUS.png); height: 100%; /* Create the parallax scrolling effect */ back ...

Establish proxied EventSource (SSE) connections via NodeJS to a backend server running on localhost

Encountering a problem with EventSource connections when using node-http-proxy v1.18.1. Everything works fine during development with create-react-app and proxy:, but once deployed to production, the connection fails and displays the following browser (chr ...

Event Listener for Scrolling Not Activating in a Next.js Client-Side Module

I am currently working on a web application using Next.js 14.0.4 and React 18.2.0. I have set out to create a scroll event listener for the entire page from a specific client-side component (namely, a header component). However, I am encountering an issue ...

D3 Treemap for handling extensive sets of data

I am uncertain if there exists a method to incorporate the desired feature. I am seeking a solution similar to zoomable treemaps, but to initially load a limited number of child levels and then dynamically add more child nodes without requiring a node clic ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

Guide to showcasing an Expo camera image in a React Native app

I have been working on an app that involves camera functionality. I have successfully taken a picture and converted it into base64 format. However, I am facing an issue when trying to display the image. Can someone please assist me in achieving this goal? ...

Above, there are two components with a scrollbar, while below there is a fixed div that remains in place when the screen

Just a heads up: below is an example with code of how I envision my interface to look, but I'm not sure if it's valid? I've been trying to create an HTML5/CSS interface that resembles the MIRC fullscreen layout (check out the image below) a ...

Finding and Selecting Dynamic CSS Elements with CSS Selector Techniques

Utilizing a tool called Stonly for adding tooltips, the CSS Selector is used to locate the HTML element for identifying the tooltip. Depending on the user input, a dynamic task list is generated. The challenge arises when trying to pinpoint a specific task ...