How to create a dropdown menu in React
Creating accessible dropdown menus is essential for navigation and user interactions in React applications, requiring proper state management and keyboard support. With over 25 years of experience in software development and as the creator of CoreUI, I’ve built countless dropdown components for enterprise applications. The most effective approach is using state to control visibility with click outside detection and keyboard event handling. This ensures accessible, user-friendly dropdown menus that work across all devices and input methods.
Use React state with useRef and event handlers to create accessible dropdown menus with proper interaction handling.
import { useState, useRef, useEffect } from 'react'
function Dropdown() {
const [isOpen, setIsOpen] = useState(false)
const dropdownRef = useRef(null)
useEffect(() => {
function handleClickOutside(event) {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
setIsOpen(false)
}
}
function handleEscape(event) {
if (event.key === 'Escape') {
setIsOpen(false)
}
}
document.addEventListener('mousedown', handleClickOutside)
document.addEventListener('keydown', handleEscape)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
document.removeEventListener('keydown', handleEscape)
}
}, [])
return (
<div ref={dropdownRef} className="dropdown">
<button onClick={() => setIsOpen(!isOpen)} aria-expanded={isOpen}>
Menu ▼
</button>
{isOpen && (
<ul className="dropdown-menu">
<li><a href="/profile">Profile</a></li>
<li><a href="/settings">Settings</a></li>
<li><a href="/logout">Logout</a></li>
</ul>
)}
</div>
)
}
This implementation uses useState to control dropdown visibility and useRef to detect clicks outside the dropdown area. The useEffect hook sets up event listeners for click outside detection and escape key handling. The component includes proper ARIA attributes like aria-expanded for screen readers and automatically closes when clicking outside or pressing Escape.
Best Practice Note:
This dropdown pattern is used throughout CoreUI components for consistent, accessible navigation. Consider adding arrow key navigation between menu items and focus management to enhance keyboard accessibility for power users.



