summaryrefslogtreecommitdiff
path: root/src/components/Input.tsx
blob: 4fb17f2605ec9bd25b4485d83d03f9cb4a9b272b (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
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 }) {
  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) => setInternalValue(e.target.value), [setInternalValue]);

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