File size: 1,098 Bytes
e0eaa09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
'use client';

import * as React from 'react';
import { useOnClickOutside } from 'usehooks-ts';
import { SelectContext } from './SelectContext';

export default function Select({
  children,
  value: controlledValue,
  onChange,
  defaultValue,
}: {
  children: React.ReactNode;
  value?: string;
  onChange?: (value: string) => void;
  defaultValue?: string;
}) {
  const [open, setOpen] = React.useState(false);
  const [internalValue, setInternalValue] = React.useState(defaultValue || '');
  const ref = React.useRef<HTMLDivElement>(null);

  const handleClickOutside = () => {
    setOpen(false);
  };

  useOnClickOutside<HTMLDivElement>(ref as React.RefObject<HTMLDivElement>, handleClickOutside);

  const value = controlledValue !== undefined ? controlledValue : internalValue;
  const handleChange = onChange || setInternalValue;

  return (
    // eslint-disable-next-line react/no-unstable-context-value
    <SelectContext.Provider value={{ open, setOpen, value, onChange: handleChange }}>
      <div className="relative" ref={ref}>{children}</div>
    </SelectContext.Provider>
  );
}