[React] Hooks - useInput

Janet·2022년 8월 22일
0

React

목록 보기
9/26
post-thumbnail

React.js > Hooks > useInput

import React, { useState, StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./styles.css";

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

const App = () => {
  const name = useInput("Name:");
  return (
    <div className="App">
      <h1>Hello</h1>
      <input placeholder="Name" {...name} />
      {/* {...name}은 value={name.value}와 같음,
    {... }는 스프레드 연산자(spread operator) */}
    </div>
  );
};

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);
  • useInput을 이용하여 입력 검증기능 만들기
import React, { useState, StrictMode } from "react";
import { createRoot } from "react-dom/client";
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 maxLength = (value) => value.length <= 10;
  // 글자 수 10글자 이하로만 입력가능
  const name = useInput("Name:", maxLength);
  return (
    <div className="App">
      <h1>Hello</h1>
      <input placeholder="Name" {...name} />
      {/* {...name}은 value={name.value}와 같음,
    "..."은 const=name에 있는 내용을 풀어내줌 */}
    </div>
  );
};

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);
profile
😸

0개의 댓글