Dropdown
The following dropdown component takes in an array of options
and displays them when you click over the component. Styling the container or the dropdown elements is very straightforward making it suit any UI. It is a single component and can be easily customized without much hassle or complexity.
No extra libraries required. Assuming you have Tailwind CSS installed
// App.jsximport React, { useState } from 'react';import Dropdown from './components/dropdown';
const App = () => { const options = [ { label: 'Option 1', value: '1' }, { label: 'Option 2', value: '2' }, { label: 'Option 3', value: '3' }, ];
const handleSelect = (option) => { console.log('Selected:', option); }; // Example
return ( <div className="p-4"> <h1 className="text-xl mb-4">Dropdown Component Example</h1> <Dropdown options={options} onSelect={handleSelect} placeholder="Select an option" /> </div> );};
export default App;
// Dropdown.jsximport React, { useState, useRef, useEffect } from 'react';
const Dropdown = ({ options, onSelect, placeholder = "Select an option", className = ''}) => { const [isOpen, setIsOpen] = useState(false); const [selectedOption, setSelectedOption] = useState(null); const dropdownRef = useRef(null);
const toggleDropdown = () => setIsOpen(!isOpen);
const handleOptionClick = (option) => { setSelectedOption(option); onSelect(option); setIsOpen(false); };
const handleClickOutside = (event) => { if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { setIsOpen(false); } };
useEffect(() => { document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, []);
return ( <div className={`relative ${className}`} ref={dropdownRef}> <button className="bg-gray-200 text-gray-800 px-4 py-2 rounded focus:outline-none focus:ring-2 focus:ring-blue-500" onClick={toggleDropdown} > {selectedOption ? selectedOption.label : placeholder} </button> {isOpen && ( <ul className="absolute z-10 mt-1 bg-white border border-gray-200 rounded shadow-lg w-full"> {options.map((option) => ( <li key={option.value} className="px-4 py-2 hover:bg-blue-500 hover:text-white cursor-pointer" onClick={() => handleOptionClick(option)} > {option.label} </li> ))} </ul> )} </div> );};
export default Dropdown;