summaryrefslogtreecommitdiff
path: root/src/components/Input.js
blob: d0683038805ff3aa176f7e32979f12bd7a1facfe (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 React from 'react';
import PropTypes from 'prop-types';

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

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

export default function Input(props) {
  return <input className={s0.input} {...props} />;
}

export function SelfControlledInput({ value, ...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={s0.input}
      value={internalValue}
      onChange={onChange}
      {...restProps}
    />
  );
}

Input.propTypes = {
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  type: PropTypes.string,
  onChange: PropTypes.func,
  name: PropTypes.string,
  placeholder: PropTypes.string
};