summaryrefslogtreecommitdiff
path: root/src/components/shared/Input.tsx
blob: 901aeb551d03fb05e8e8d54d90e973d55d30ef07 (plain)
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
39
40
41
42
import cx from 'clsx';
import React from 'react';

import s0 from './Input.module.scss';

const { useState, useRef, useEffect, useCallback } = React;

export default function Input({
  className,
  ...props
}: React.InputHTMLAttributes<HTMLInputElement>) {
  return <input className={cx(s0.input, className)} {...props} />;
}

export function SelfControlledInput({
  value,
  className,
  ...restProps
}: React.InputHTMLAttributes<HTMLInputElement>) {
  const [internalValue, setInternalValue] = useState(value);
  const refValue = useRef(value);
  useEffect(() => {
    if (refValue.current !== value) {
      // ideally we should only do this when this input is not focused
      setInternalValue(value);
    }
    refValue.current = value;
  }, [value]);
  const onChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => setInternalValue(e.target.value),
    [setInternalValue],
  );

  return (
    <input
      className={cx(s0.input, className)}
      value={internalValue}
      onChange={onChange}
      {...restProps}
    />
  );
}