Implementing a dynamic navigation bar that expands and collapses on mouse hover in a React application

I have a side navigation bar on my webpage that I obtained from a React Bootstrap website, so the class names are already pre-loaded. Instead of using a toggle hamburger icon to expand or collapse the navigation, I want to achieve this functionality based on mouse enter and leave events. Below is my current attempt at implementing this feature. I have created two event handlers for mouse enter and leave, and used inspect element to identify the class names when the navigation is expanded and collapsed.

However, I encountered an issue where assigning these class names dynamically based on mouse position did not work as expected. Can anyone help me with solving this problem?

class App extends Component {
  render() {

    let sideNav;

    const mouseEnter = e => {
      sideNav = "sideNav sidenav---sidenav---_2tBP sidenav---expanded---1KdUL";
      console.log("Mouse entered");
      return sideNav;
    }    

    const mouseLeave = e => {
      sideNav = "sidenav---sidenav---_2tBP sidenav---collapsed---LQDEv";
      console.log("mouse left");
      return sideNav;
    }

    return (
      <div className="App container">
        <div>
          <SideNav 
            onMouseEnter={mouseEnter} 
            onMouseLeave={mouseLeave}
            className={this.sideNav}
            onSelect={(selected) => {
                // Add your code here
            }}
          >
            <SideNav.Toggle  />
            <SideNav.Nav  defaultSelected="home">
                <NavItem eventKey="home">
                    <NavIcon>
                        <Link to="/"><img src={Dash}/></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/">Dashboard</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="sites">
                    <NavIcon>
                      <Link to="/sites"><img src={Site} /></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/sites">Sites</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="tours">
                  <NavIcon>
                    <Link to="/tours"><img src={Tour}/></Link>
                  </NavIcon>
                  <NavText>
                      <Link to="/tours">Tours</Link>
                  </NavText>
                </NavItem>
                <NavItem eventKey="media">
                    <NavIcon>
                      <Link to="/media"><img src={Media}/> </Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/media">Media</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="newSite">
                    <NavIcon>
                        <Link to="/newSite/details"><img src={NewSite} /></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/newSite/details">Add new Site</Link>
                    </NavText>
                </NavItem>
                <NavItem eventKey="profile">
                    <NavIcon>
                        <Link to="/profile"><img src={Profile} /></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/profile">Profile</Link>
                    </NavText>
                </NavItem>

            </SideNav.Nav>
          </SideNav>
        </div>
        <Routes />
      </div>
    );
  }
}

export default App;

Answer №1

I recommend utilizing sideNav within your component's state, as this is the preferred method in React for re-rendering an element. Every time you use setState, React looks for changes in the code to display what you desire. If you only update your variable without using setState, React will not be aware of those changes. Your code may function as if you are doing this:

class App extends Component {
  constructor(){
      super();
      this.state = {
        sideNav: ''
      }
  }

    const mouseEnter = e => {
      this.setState({sideNav: "sideNav sidenav---sidenav---_2tBP sidenav---expanded---1KdUL"});
      console.log("Mouse entered");
    }    

    const mouseLeave = e => {
      this.setState({sideNav: "sidenav---sidenav---_2tBP sidenav---collapsed---LQDEv"});
      console.log("mouse left");
    }

  render() {

    return (
      <div className="App container">
        <div>
          <SideNav 
            onMouseEnter={mouseEnter} 
            onMouseLeave={mouseLeave}
            className={this.state.sideNav}
            onSelect={(selected) => {
                // Add your code here
            }}
          >
            <SideNav.Toggle  />
            <SideNav.Nav  defaultSelected="home">
                <NavItem eventKey="home">
                    <NavIcon>
                        <Link to="/"><img src={Dash}/></Link>
                    </NavIcon>
                    <NavText>
                        <Link to="/">Dashboard</Link>
                    </NavText>
                </NavItem>

                {/* Additional NavItems */}

            </SideNav.Nav>
          </SideNav>
        </div>
        <Routes />
      </div>
    );
  }
}

export default App;

To see how this concept works in more detail, you can visit https://reactjs.org/docs/state-and-lifecycle.html

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

Challenges with displaying the appropriate user interface in the dashboard according to different roles

My current project involves rendering different UI components based on selected roles such as brands, agency, or influencer. However, despite my efforts to implement the logic for this functionality, the correct UI is not being loaded and I'm struggli ...

Delay in Updating Nativescript Slider Value

After developing a metronome using the Nativescript Slider here to adjust speed (interval), I encountered an issue with incorrect updating of values. The code initially worked well, allowing real-time speed changes: app.component.html <Slider #sl min ...

Can Big Data flow on Mongo DB be effectively simulated?

My idea involves creating a server with routes and models to be hosted on Heroku for processing requests. I plan to make incremental requests to the server until they qualify as Big Data. I suspect there may be limitations on how many consecutive requests ...

Is the Three.js and React-three-fiber model appearing pitch black?

This particular model appears completely black when loaded, unlike others. Link to the problematic model Does anyone have any insights into why this might be happening? All other GLB files load correctly with textures, but this particular one is causing ...

What specific blur algorithm is utilized by the Flash platform within their blur filter implementation?

I'm in the process of translating AS3 code to JavaScript, and I've come across an AS3 application that utilizes Flash's built-in Blur Filter Could someone provide insight into the blurring algorithm used by this filter or suggest ways to re ...

Creating a line break in a Vue.js confirmation dialog is a helpful feature that can be achieved with a

Is there a way to add a new line after the confirmation dialog question and insert a note below it? this.$dialog.confirm("Create Group","Would you like to create group "+ this.groupName +"?<br/>(NOTE: Selected project or empl ...

Discovering the channel editor on Discord using the channelUpdate event

While working on the creation of the event updateChannel, I noticed that in the Discord.JS Docs, there isn't clear information on how to identify who edited a channel. Is it even possible? Below is the current code snippet that I have: Using Discord. ...

How does ES6 impact the connection between Angular, jQuery, and Vue.js?

Searching for tutorials on implementing ES6 with Vue.js but struggling to find a clear connection between the two. Curious if ES6 can be utilized directly or if it requires integration with libraries such as jQuery, Angular, or Vue.js. If using a script ...

What could be causing the createReadStream function to send a corrupted file?

My current task involves generating a file from a URL using the fs module to my local system. Initially, everything seems successful. However, when attempting to post this file into a group using the createReadStream() function, I encounter an issue where ...

Incorporate font assets from the bundled ReactJS library in the npm package for Rollup

I am currently in the process of bundling a reactjs library using rollup to generate an npm package containing all my UI components. However, I have encountered an issue with the font icons. Whenever I attempt to utilize an icon from another react app, I e ...

Discord.js Lock Command Implementation

I've developed a lock command for discord.js, but every time I try to run the command, I encounter an error. Here's the code snippet: module.exports = { name: "lock", description: "Lock", async run(client, message ...

Create fluidly changing pictures within varying div elements

Hello there! I have a form consisting of four divs, each representing a full page to be printed like the one shown here: https://i.sstatic.net/w7N6E.png I've successfully created all the controls using AJAX without any issues. Then, I load the image ...

How can JSON data objects be transmitted to the HTML side?

I created a JSON object using Node JS functions, and now I'm looking to transfer this data to the HTML side in order to generate a table with it. However, I'm encountering difficulties sending the JSON object over because of my limited experience ...

Looking for a drum set with clickable buttons? Having trouble changing the background color in CSS/HTML? Wondering how to map keyboard keys to HTML buttons?

Behold my HTML creation: <H1> <center> EPIC GUITAR JAM </center> </H1> <img class="guitar" src="guitar.jpg" /> <button class="strum" onclick="Strum()"> Strum Chord </button> <button class="pluck" o ...

Immerse yourself in a world of virtual reality with the cutting-edge VR Vide

Currently, I am in the process of developing a virtual panoramic tour that features various panoramas linked together with hotspots. Each panorama contains a video hotspot that plays a video. However, I have encountered an issue where every time a new sce ...

ReactJS Material-UI Tooltip and Popper overlapping issue

How can I make the MUI tooltip appear beneath the MUI Popper, with the popper overlapping the tooltip? Is there a way to modify the z-index for only a specific portion of the elements without affecting the global styles when using external CSS? Here is a ...

Using the JavaScript selectionchange event to target a specific element exclusively

I am looking for a way to incorporate a JavaScript selectionchange event on a specific div element. The goal is to display a highlighter box when the user selects text from the DOM. I was able to achieve this functionality for web using an onmouseup event, ...

What is the best way to find the maximum and minimum values within a JSON object that is populated from user inputs using only JavaScript?

Here is a simple form that stores data at the following link: https://jsfiddle.net/andresmcio/vLp84acv/ var _newStudent = { "code": code, "names": names, "grade": grades, }; I'm struggling to retrieve the highest and lowe ...

Encountering an issue with MUI 5 where it is unable to access properties of undefined when utilizing makestyles

I recently finished building a react app using MUI-5 and everything was running smoothly. However, I've encountered a strange issue where my app refuses to start and I'm bombarded with multiple MUI errors. These errors started popping up after I ...

Organizing menu options into subcategories using jQuery UI for easy sorting

I am currently working on a horizontal jQuery menu item that includes the sortable option and has one submenu. My goals for this project are as follows: To keep the menu item with the submenu locked at the end of the list To be able to drag menu items fr ...