React Hooks_useInput

2021. 7. 7. 23:01Big Dreamer_Developer/React

export const useInput = (initialValue, validator) => {
  const [value, setValue] = useState(initialValue);
  const onChange = (event) => {
    const {
      target: { value },
    } = event;
    let willUpdate = true;
    if (typeof validator === 'function') {
      willUpdate = validator(value);
    }
    if (willUpdate) {
      setValue(value);
    }
  };
  return { value, onChange };
};

const App = () => {
  const maxLen = (value) => value.length <= 10;
  const name = useInput('Mr.', maxLen);
  return (
    <div className="App">
      <h1>Hello</h1>
      <input placeholder="Name" {...name} />
    </div>
  );
};

'Big Dreamer_Developer > React' 카테고리의 다른 글

React Hooks_useState  (0) 2021.07.07
React Hooks_useTabs  (0) 2021.07.07
About the Router  (0) 2021.07.06
Rendering The Movies  (0) 2021.07.03
Fetching Movies from API  (0) 2021.07.03