generate a state with a variable attribute

Utilizing React JS in my current project involves a two-level menu system. Upon hovering over a menu item, the corresponding sub-menu should appear and disappear when the mouse leaves the area. However, a challenge arises when all sub-menus appear simultaneously due to a single shared state. I am seeking guidance on implementing a dynamic state that enables only the relevant sub-menu to display upon hover.

The 'App.js' file contains:

// Code snippet

The 'App.css' file includes styling rules such as:

.container{
  background-color: #eee;
  height: 40px;
}
.main__items{
  display: flex;
  position: relative;
}
.main__item{
  margin: 0 20px;
  cursor: pointer;
}

The 'Sub.js' file is crucial for rendering sub-menu items based on user interaction:

// Code snippet

The 'Sub.css' file dictates the appearance of the sub-menu items:

.sub__items{
    position: absolute;
    top: 40px;
    background-color: bisque;
}
.sub__item{
    margin: 10px;
}

Your insights or assistance would be highly appreciated.

Answer №1

To keep track of the submenu that is currently open for a menu item, you can use the following method. When a menu is clicked, store its id and then display the corresponding submenu.

    const [activeSubMenuId, setActiveSubMenuId] = useState(null);

    const showSubMenu = (id) => {
        setActiveSubMenuId(id);
    }

    const hideSubMenu = () => {
        setActiveSubMenuId(null);
    }

    const mainMenuList = mainMenuArr.map(main => {
        return (
            <li onMouseEnter={() => showSubMenu(main.id)} onMouseLeave={() => hideSubMenu(main.id)} key={main.id} id={main.id} className='main__item'>
                {main.name}
                <Sub isOpen={activeSubMenuId === main.id} subItems={main.items}/>
            </li>
        );
    })

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

Error: Unable to execute setState in React Native

Why am I receiving an error stating that this.setState is not a function? I'm having trouble understanding why my code isn't working as expected. import React from 'react'; import axios from 'axios' import { StyleSheet, Text ...

Retrieve the values from hidden input fields that share the same name

How do I retrieve values from cName inputs? <form method="post" action=""> <input type="hidden" name="cName" value="test1" /> <input type="submit" name="get" /> </form> <form method="post" action=""> <input type="hi ...

Is there a way for me to customize the appearance of the drop-down panel in a select box to feature rounded corners specifically for the Chrome browser?

Hey there! Currently working on an Angular 5 application where I need to style a select box with rounded corners for the options panel in Chrome. Would appreciate any tips or suggestions on achieving this using CSS styles. Please refer to the image linked ...

'Mastering the implementation of promises in React context using TypeScript'

I've been diving into the world of incorporating TypeScript in React and I'm facing a challenge with implementing async functions on context. The error that's popping up reads as follows: Argument of type '{ userData: null; favoriteCoc ...

Mongo automatically generates an index with a null key/value pair

After successfully creating a new user using mongoose at a certain route, I noticed that the validation appears in the console and the user is stored in the mongo database. However, when attempting to create a second user with a different username, an erro ...

Tips for automatically loading a new page or URL when a user scrolls to the bottom

I am working on implementing infinite scroll functionality, where a new page loads automatically when the user reaches the bottom of the page or a particular div. Currently, I have this code that loads a new page onclick. $("#about").click(function(){ ...

What about dynamically generating content with WebUserControl?

I have created a custom WebUserControl with three HTML controls, two buttons, and one input text. Each control has a static ID, which I believe is not incorrect. The control events are set up using JavaScript. After delivering the control to the client, th ...

Reusing a lazy-loaded module across multiple applications

Currently, I am working on an enterprise Angular 2 application with numerous lazy loaded modules. A new project came up where I needed to reuse a module that was previously created for the main app. After researching online, the only solution I found was ...

I can't seem to figure out why I keep running into a 403 error and why my Delete API isn't functioning

Need Assistance as a Beginner Working on a MERN Project and struggling with making the Delete API function from the front-end. The Delete API works perfectly when tested through Postman, but fails to work from the front-end. Below is the code snippet of t ...

Having trouble with the JavaScript code for a basic GPA calculator?

I am having issues with my code for a basic grade calculator. Even though I can input numbers, the final grade is not displayed on the screen. Can someone please help me identify what mistake I might be making? Please ignore the Japanese text, as it's ...

Find common connections on Facebook using an app PRIOR to downloading it

Is there a way to programmatically find mutual friends between myself and an application or page? For instance, in the scenario shown below: In the image above, it's evident that prior to installing the Causes App (1) I can observe that myself and t ...

Encountering issues with npm package serving in conjunction with React

Looking to implement the serve package with a React App, I followed these steps: 1. Run npm install serve --s 2. Replace the npm start command in package.json as shown below: scripts": { "start": "serve -s build", " ...

Altering the image hover behavior in Firefox to a custom setting

I'm encountering an issue with my image where it appears disabled. When I hover over it, I want the cursor to change to 'pointer', and when it's enabled I want it to be a 'hand'. This functionality works correctly in IE, but i ...

Refreshing the list in a Next.js to-do application post-deletion: a step-by-step guide

I am currently developing a basic to-do application using Next.js, TypeScript, and Axios. I have successfully implemented the delete functionality for tasks, but I am facing an issue with refreshing the tasks list after deletion. I would appreciate any s ...

Guide to exporting a ReactJS + Typescript component to be used in Vanilla JavaScript and HTML

I have a ReactJS component along with its sub-components styled with CSS. I'm looking for a way to export my component for VanillaJS and HTML without having to import React@17 or 18. If there is an easier method or any alternative suggestions instead ...

associating functions with various events that require arguments

I am working with two event listeners that trigger separate functions, but I believe it might be more efficient to have them trigger the same function instead. These event listeners are monitoring keystrokes and the mouse wheel. $(document).mousewheel(on ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

Which tools are essential for setting up a React and Babel development environment?

Currently in the process of setting up react with Babel. I'm confused about the various installation options available. Can someone please explain the differences and recommend which ones I should select? npm install --save-dev babel-preset-react npm ...

Customized interfaces utilizing generic components

Here is my simplified question. interface Identity{ name: string; } Next, we have a generic interface. interface State<T extends Identity>{ [T.name] : StateContainer<T> } Unfortunately, this approach fails and the following error is ...

The data source retrieved through the "get" API method is missing from the mat-table

Recently, I've started working with angularCLI and I'm facing an issue in creating a table where the dataSource is fetched from a fake API. Let me share my component class: import { Component, OnInit } from '@angular/core'; import { Fo ...