[강의노트] Hooks - useInput

Tia Hwang·2020년 4월 20일
0

[Nomad] React Hooks

목록 보기
3/6

useInput()

  • 기본적으로 input을 업데이트함
  • 사용예제
    • {...name}
      => value={name.value} onChange={name.onChange}
import React, { useState } from "react";

const useInput = initialValue => {
  const [value, setValue] = useState(initialValue);
  const onChange = e => {
    console.log(e.target);
  };
  return { value, onChange };
};

const App = () => {
  const name = useInput("Ms.");
  return (
    <div>
      <h1>Hello</h1>
      <input placeholder="Name" {...name} />
    </div>
  );
};

export default App;
  • validator 함수 추가
import React, { useState } from "react";

const useInput = (initialValue, validator) => {
  const [value, setValue] = useState(initialValue);
  const onChange = e => {
    const {
      target: { value }
    } = e;
    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("Ms.", maxLen);
  return (
    <div>
      <h1>Hello</h1>
      <input placeholder="Name" {...name} />
    </div>
  );
};

export default App;
profile
프론트엔드 개발자로 취업하기

0개의 댓글