Problem with the visibility of the drop-down menu when hovering over it

I am currently developing a ReactJS application using reactstrap. One of the components I have created is a dropdown with submenus nested inside.

My goal is to make the submenus appear when hovering over the dropdown, and if there are multiple dropdowns (n in total), only the submenus related to the hovered item should be displayed.

This is the code snippet I have tried:

<Dropdown
  className="d-inline-block"
  onMouseOver={this.onMouseEnter}
  onMouseLeave={this.onMouseLeave}
  isOpen={this.state.dropdownOpen}
  toggle={this.toggle}
>
  <DropdownToggle caret>Dropdown1</DropdownToggle>
  <DropdownMenu>
    <DropdownItem header>Submenu 1</DropdownItem>
    <DropdownItem>Submenu 1.1</DropdownItem>
  </DropdownMenu>
  &nbsp;&nbsp;&nbsp;
  <DropdownToggle caret>Dropdown2</DropdownToggle>
  <DropdownMenu>
    <DropdownItem header>Submenu 2</DropdownItem>
    <DropdownItem>Submenu 2.1</DropdownItem>
    <DropdownItem>Submenu 2.2</DropdownItem>
  </DropdownMenu>
  &nbsp;&nbsp;&nbsp;
  <br />
  <br />
  <DropdownToggle caret>Dropdown3</DropdownToggle>
  <DropdownMenu>
    <DropdownItem header>Submenu 3</DropdownItem>
    <DropdownItem>Submenu 3.1</DropdownItem>
    <DropdownItem>Submenu 3.2</DropdownItem>
    <DropdownItem>Submenu 3.3</DropdownItem>
  </DropdownMenu>
</Dropdown>

Click here for a live demo

Desired Outcome:

If you visit the link above, you will see a horizontal menu that displays its submenu when hovered over. My objective is to replicate this behavior in my React application.

Answer №1

  1. To improve your code, consider organizing those menus into a single <Dropdown> component.
  2. Make sure to assign an event handler for each menu item.
  3. You can simplify the process of setting event handlers by using Array.prototype.map.
import React from "react";
import {
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem
} from "reactstrap";

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.onMouseEnter = this.onMouseEnter.bind(this);
    this.onMouseLeave = this.onMouseLeave.bind(this);
    this.state = {
      dropdownOpen: -1
    };
    this.toggle = this.toggle.bind(this);

    this.menus = [
      {
        title: "Bathroom",
        submenus: [{ title: "Toilets" }, { title: "Toilet seats" }]
      },
      {
        title: "Kitchen",
        submenus: [{ title: "Farmhouse Sinks" }, { title: "Cast Iron Sinks" }]
      }
    ];
  }

  onMouseEnter(current) {
    this.setState({ dropdownOpen: current });
  }

  onMouseLeave() {
    this.setState({ dropdownOpen: -1 });
  }

  toggle() {}

  render() {
    return (
      <div>
        {this.menus.map((menu, i) => (
          <Dropdown
            className="d-inline-block"
            onMouseOver={e => this.onMouseEnter(i)}
            onMouseLeave={this.onMouseLeave}
            isOpen={this.state.dropdownOpen === i}
            toggle={this.toggle}
          >
            <DropdownToggle caret>{menu.title}</DropdownToggle>
            <DropdownMenu>
              {menu.submenus.map((submenu, i) => (
                <DropdownItem header>{submenu.title}</DropdownItem>
              ))}
            </DropdownMenu>
          </Dropdown>
        ))}
      </div>
    );
  }
}

stackblitz: https://stackblitz.com/edit/reactstrap-v6-qsffjj

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

What is the best way to host a NextJs application within a Spring Boot application?

Currently, I have a Spring Boot REST API service up and running in Tomcat. In addition, there is a NextJS UI application running on the Node.js server. My goal now is to have the NextJS app served by the Tomcat server. What are the essential steps that ...

How can one effectively generate room within an HTML/CSS file?

Within my div element, I have organized rows of three images each. These images are uniform in size. Previously, I used small, completely clear transparent images to create spaces between the images by explicitly setting their height and width. An example ...

PHP dropdown menu is a dynamic feature that provides users

Can anyone help me identify the issue with this code? I am struggling to display the sub menu... I suspect the problem lies in the section where I retrieve the sub menu from the database. However, upon inspection, everything seems correct... It's po ...

Animation showing on the progress bar is not correctly halted

I am encountering a problem with handling an animation of a progress bar in my code. The issue arises when I pause the animation, as it seems to slightly backtrack instead of pausing at the correct position upon clicking a button. Can someone help identify ...

In React, retrieve the value of the previously clicked radio button when a new one is

My MUI radio buttons are set up to gather filter criteria for an object. After filtering the object, I display the filtered results in an owl carousel. However, I have encountered an issue where clicking on a radio button always selects the previously cl ...

Utilizing CSS/HTML to optimize code for mobile applications

Looking for some help with implementing the Upcoming Events part from this code snippet: https://codepen.io/AbhijithHebbarK/pen/boKWKE .events-details-list{ opacity:0; transition: all 0.3s ease-in-out; position: absolute; left: 0; rig ...

Is there a way to deactivate a full HTML page during an event, similar to when using a JavaScript alert?

I'm currently working on a JSP/HTML web page where I need to disable or "gray out" the entire page when a button is clicked. This will prevent the user from accessing any other elements on the page until it's disabled. Any ideas on how to achiev ...

Attempted to remove Child Div using Jquery, but it did not get removed as expected

Trying to remove child divs inside a parent div? There are several methods, such as: $(".ChildDiv").html(""); $('.ChildDiv > div').remove(); $(".ChildDiv").html(""); $("#ParentDiv").html(""); $(".ChildDiv div").remove(); $(".ChildDiv di ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

The website is failing to adapt properly to smaller screen sizes

I would share some code here, but it might be easier for you to just check out the URL instead. The issue is that the website was responsive across different screen sizes at first, but after making some changes in the CSS and HTML, it's not working pr ...

Assigning the Style property to an element using a string that includes HTML tags

My HTML string is populated with elements such as button, li, span, and more. I am looking to add specific styles to buttons based on their class name. For example, if button.btn { some styles } and button.btn-success { some other styles } O ...

MUI: (Autocomplete) The input given for Autocomplete is not valid

While attempting to load data into an MUI Autocomplete, I encountered this message in the console. React-hook-form and yup are being used for form validation. Image displaying the warning To showcase my issue, I have set up a CodeSandbox. In this example, ...

Tips for creating an expandable div with floated content

I am looking to create a flexible div that expands based on its content. Inside this div, there are two floated left divs with fixed widths. These inner divs should also expand according to their text content. To clear the floats, there is another div wi ...

Issue arising with the resizing of the image in the main section, as it is shrinking prematurely before reaching the designated width

Desired Outcome Current Situation Currently, I am in the process of creating a responsive hero section where I aim to maintain the image at full size until the window width reaches below 1300px. However, I have observed that the image starts to shrink mu ...

Resources for ExpressJS

New to ExpressJS and trying to figure out how to reference images stored in the /public/images/ directory in my /public/stylesheets/styles.css The code snippet below doesn't seem to be working for me: .home-bg { background-image:url('../ima ...

Click on the sort icon in React JS to change its state

I need to update the sort icon in my table header when a user sorts a column. Here is the current implementation of my sorting function: var headerColumns = []; var IconType = 'triangle'; var IconSort = 'top'; var onToggleO ...

Create a mobile-friendly version of the website that retains all the functionality and features of the desktop

Currently, I am in the process of optimizing my website for mobile devices. However, creating a separate subdomain and folder for a new mobile version is proving to be a challenge since it was not originally requested. How can I ensure that the website ap ...

Attempting to align a banner image in the middle using CSS styling

I'm having some trouble getting the banner image to be centered on all screen sizes. It looks good on smaller screens, but on larger ones it seems to be shifting to the left. Here's what I've attempted so far: .banner { padding-top: ...

Having difficulty formatting text alignment using CSS

Is there a way to maintain the alignment of text in the output of the 'About' section even when the content changes dynamically? I want the new line to appear just below 'Lorem', but currently, it shifts below the colon(:). Since the le ...

Applying toggle() using css to manipulate various elements at once

Is there a way to toggle multiple divs of varying heights, all with the same class? What is the most effective approach to achieve this? http://jsfiddle.net/hS6RH/41/ $('.smallify').on('click', function() { if ($(this).parent(&apo ...