코드 테스트는 CodeSandBox에서 하시면 됩니다.


import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

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 <= 15;
  const hasAlpha = value => !value.toUpperCase().includes("F");
  const name = useInput("Hyunwoo Hwang", maxLen);
  const name2 = useInput("Test Name", hasAlpha);

  return (
    <div className="App">
      <h1>
        Hello{" "}
        <span style={{ color: "blue", fontSize: "15pt" }}>{name.value}</span>
      </h1>
      <input placeholder="Name" {...name} />
      <input placeholder="Name" {...name2} />
    </div>
  );
};

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

 

+ Recent posts