Hook - useInput

원종서·2021년 8월 25일
0

hook

목록 보기
1/11
import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const useInput = (initValue, validator) => {
  const [value, setValue] = useState(initValue);
  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 maxLength = (value) => value.length <=10;
	// 글자수 10개 이상 방지
  const name = useInput("Mr.", maxLength);
  return (
    <div className="App">
      {/* // value={name.value} onChange={name.onChange}
    // {...name} 같다 */}
      <input placeholder="What's your name?" {...name} />
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

0개의 댓글