Calvin Goodale, Developer - Blog
c g o o d a a l e . . c o m
  • About
  • Links
  • Blog
flask sql hackerrank django javascript gamedev games professional development react poker hack reactor SDC docker AWS BOC cloud css PHP adventofcode html

Creating a Navigation Drop-down in React

Posted by Calvin on December 13, 2023 at 4:17 PM

Categories: react html

For an MVP I'm currently working on, the client wanted some of the top navigation menu items to have drop-downs containing other nagivation links. I'm sure there are many ways to implement this, but this is how I decided to do it:

  • Create a NavDropdown component that takes dropdownItems props and maps them to NavLinks:

    NavDropdown component:

    import { NavLink } from 'react-router-dom';
    
    function NavDropdown({dropdownItems}) {
      return (
        <div className='nav-dropdown'>
          {
            dropdownItems.map(item => {
              return <NavLink className='nav-dropdown-item' to=`/${item}`>{item}</NavLink>
            })
          }
        </div>
      );
    }
    
    export default NavDropdown;
  • Import the NavDropdown component into the NavBar component, and pass it the appropriate text.
  • Use onMouseEnter and onMouseLeave events to set the hoveredItem state in the NavBar component, and conditionally render the NavDropdown component based on this state.

    NavBar component:
    import { useState } from 'react';
    import { NavLink } from 'react-router-dom';
    
    import NavDropdown from './NavDropdown';
    
    function NavBar() {
    
      const [hoveredItem, setHoveredItem] = useState('')
    
      return (
        <div id='navbar' className='relative mx-4 flex'>
          <NavLink className='top-nav-item' to='/'>Home</NavLink>
          <NavLink className='top-nav-item' onMouseEnter={() => setHoveredItem('about')} onMouseLeave={() => setHoveredItem('')} to='/about'>
            About
            {hoveredItem === 'about' &&
              <NavDropdown dropdownItems={['Link1', 'Link2', 'Link3']}/>
            }
          </NavLink>
          <NavLink className='top-nav-item' to='/signup'>SignUp</NavLink>
        </div>
      );
    }
    
    export default NavBar;

I still have a few things to clean up, but I'm pretty happy with how it functions, and thanks to conditional rendering I didn't have to use any CSS display property nonsense.


0 Comments

© 2019 cgoodale