https://nomadcoders.co ์์ ๊ฐ์๋ฅผ ๋ฃ๊ณ ์ ๋ฆฌํ ๋ด์ฉ ์ ๋๋ค.
import React, {useState} from "react";
import ReactDOM from "react-dom";
const useInput = (inititalValue) => {
const[value, setValue] = useState(initialValue);
const onChange = (e) => {
}
return { value, onChange }
};
const App = () => {
const name = useInput("Lee");
return (
<div className="App">
<h1> hello </h1>
// <input placeholder="Name" value={name.value} onChange={name.onChange}/>
// <input placeholder="Name" value={...name}/>
// ๋๋ฌด ๊ธธ์ด์ง๋ฏ๋ก ๋ชจ๋ unpack ํด์ค
<input placeholder="Name {...name}>
</div>
)
}
import React, { useState } from "react";
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 }
};
export default useInput;
import React from "react";
// ๋ถ๋ฆฌ ํ์ผ๋ฏ๋ก import ํด์ ์ฌ์ฉ
import useInput from "./Hooks/useInput";
const App = () => {
const maxLen = value => value.length <= 10;
// const restrictChar = value => !value.includes("@");
const name = useInput("Lee", maxLen);
return (
<div className="app">
<input placeholder="Name" {...name} />
</div>
)
}
export default App;
์๊ฐ ํ์ ์ฌ์ ๊ฐ ์์ผ๋ฉด ์ฌ๋ฌ๊ฐ์ง ๊ฒ์ฆ์ ํ์ธํ ์ ์๋๋ก ํด๋ณผ ๊ฒ์ด๋ค.