29 - Responsive Navigation Menu with Dropdowns

Description

Develop a navigation menu that adapts to different screen sizes and includes dropdown menus for sub-navigation links. Consider the following features:

  • Responsive Design: The menu should adjust its layout and styling appropriately for various viewports (desktop, tablet, mobile).

  • Dropdown Menus: Main navigation items with sub-items should display dropdown menus on hover or click.

  • Accessibility: Ensure the menu is navigable using keyboard interactions and screen readers.

  • Clear Visual Hierarchy: Establish a clear visual structure for the menu, with primary and secondary navigation elements distinguishable.

Algorithm

  1. HTML Structure:

    • Create a semantic structure with nav, ul, and li elements.

    • Use appropriate heading elements for primary navigation items.

    • Employ ARIA attributes for accessibility (e.g., aria-expanded, aria-haspopup).

  2. CSS Styling:

    • Define styles for menu elements, including hover states and dropdown menus.

    • Implement media queries to adjust layout and styles for different screen sizes.

  3. JavaScript Functionality (if needed):

    • Toggle dropdown visibility on hover or click events.

    • Handle keyboard interactions for menu navigation.

    • Implement animations or transitions for visual effects.

Code

import React, { useState } from 'react';

function ResponsiveNavbar() {
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const toggleDropdown = () => {
    setDropdownOpen(!dropdownOpen);
  };

  return (
    <nav>
      <ul>
        <li>
          <a href="#">Home</a>
        </li>
        <li>
          <a href="#">About</a>
        </li>
        <li>
          <a href="#" aria-haspopup="true" aria-expanded={dropdownOpen} onClick={toggleDropdown}>
            Services
          </a>
          <ul className="dropdown" style={{ display: dropdownOpen ? 'block' : 'none' }}>
            <li><a href="#">Service 1</a></li>
            <li><a href="#">Service 2</a></li>
            <li><a href="#">Service 3</a></li>
          </ul>
        </li>
        <li>
          <a href="#">Contact</a>
        </li>
      </ul>
    </nav>
  );
}

export default ResponsiveNavbar;

Explanation

  • State Management: The useState hook manages the dropdownOpen state for controlling dropdown visibility.

  • Event Handling: The toggleDropdown function handles clicks on the "Services" link to toggle the dropdown.

  • Conditional Rendering: The dropdown's display style is conditionally set based on the dropdownOpen state.

  • ARIA Attributes: ARIA attributes are included for accessibility, indicating the presence of a dropdown and its expanded state.

Additional notes

Extend with features like:

  • Hamburger Menu for smaller screens to conserve space.

  • Smooth animations for dropdown transitions.

  • Sticky menu bar for persistent navigation.

Last updated