Dropdown.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { useState, FunctionComponent, useRef } from 'react'
  2. import { useOnClickOutside } from '../../lib/onClickOutside'
  3. import { customEvent } from '../../lib/customEvent'
  4. export interface IDropdown {
  5. items?: IDropdownItem[]
  6. name: string
  7. value: string
  8. onChange: (event: CustomChangeEvent) => void
  9. }
  10. export interface IDropdownItem {
  11. key: string | number
  12. title: string
  13. }
  14. const Dropdown: FunctionComponent<IDropdown> = ({
  15. items = [],
  16. name,
  17. value,
  18. onChange,
  19. children,
  20. }) => {
  21. const [open, setOpen] = useState(false)
  22. const [active, setActive] = useState<undefined | IDropdownItem>()
  23. const ref = useRef<HTMLDivElement>(null)
  24. useOnClickOutside(ref, () => setOpen(false))
  25. const activeItem = active && items?.find((item) => item.key === active.key)
  26. return (
  27. <div id='dd-container' ref={ref}>
  28. <div id='dd-header' onClick={() => setOpen(!open)}>
  29. {activeItem ? activeItem.title : 'please select one'}
  30. </div>
  31. <ul id='dd-items'>{items}</ul>
  32. <div>{open ? 'open' : 'closed'}</div>
  33. <div>{active}</div>
  34. <style jsx>{`
  35. #dd-container {
  36. position: relative;
  37. margin: 0;
  38. padding: 0;
  39. }
  40. #dd-header p {
  41. background-color: #99555533;
  42. margin: 0;
  43. padding: 0;
  44. }
  45. #dd-items {
  46. display: ${open ? 'block' : 'none'};
  47. position: absolute;
  48. width: 100%;
  49. max-height: 300px;
  50. z-index: 5;
  51. overflow-y: scroll;
  52. margin: 0;
  53. padding: 0;
  54. background-color: #55995533;
  55. }
  56. `}</style>
  57. </div>
  58. )
  59. }
  60. export default Dropdown