useInput
import React, {useState} from "react";
import ReactDOM from "react-dom";
const useInput = initialValue = {
const [value, setValue] = useState(initialValue);
return {value};
};
const App = () => {
const name = useInput("Mr.");
return (
<div className="App">
<h1>Hello</h1>
<input placeholder="Name" value={name.value} />
<div>
`);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
- input를 업데이트함
- useInput은 initialValue를 받음
- useInput은 value를 return하고 name과 value가 같아지고 value는 name.value를 가지게 됨
<input placeholder="Name" {...name} />
- value={name.value} 대신에 {...name} 사용가능
- name 안에 있는 모든 것들을 풀어줌
- name은 name.value가 되서 똑같아짐
function 사용
import React, {useState} from "react";
import ReactDOM from "react-dom";
const useInput = initialValue = {
const [value, setValue] = useState(initialValue);
const onChange = event => {
console.log(event.target);
};
return {value};
};
const App = () => {
const name = useInput("Mr.");
return (
<div className="App">
<h1>Hello</h1>
<input placeholder="Name" {...name} />
<div>
`);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
- 다른 function에서 이벤트를 처리할 수 있음
- react component가 아닌 완전히 다른 function
- 이벤트를 분리된 파일, 다른 entity에 연결해서 처리할 수 있음
유효성 검사 기능 추가
import React, {useState} from "react";
import ReactDOM from "react-dom";
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 <= 10;
const name = useInput("Mr.", maxLen);
return (
<div className="App">
<h1>Hello</h1>
<input placeholder="Name" {...name} />
<div>
`);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
- willUpdate는 true이므로 항상 업데이트가 됨
- name을 사용하여 useInput에 Mr와 maxLen을 넣어줌
- validator은 매번 변경됨
- validator 타입이 function이라면 willUpdate에 validator의 결과를 업로드
- validator는 maxLen을 뜻하고
- 그 결과는 True 나 False가 됨
- value의 길이가 10보다 작으면 true가 되고 Update를 할 수 있음
- willUpdate가 true라면 화면에 Mr.를 업데이트 함
- function은 검증기능을 가지고 있음
- boolean(true, false) 타입을 return 한다면 validator가 실행될 수 있도록 기다리고 validator가 true라면 willUpdate가 true가 되어 실행되고 value를 세팅할 수 있음
공부 강의 : 노마더코더 - 실전형 리액트 Hooks 10개
'Front > React.js' 카테고리의 다른 글
Fetch API 란? (0) | 2025.02.12 |
---|---|
useTabs Hooks (0) | 2025.01.10 |
USESTATE Hooks (0) | 2025.01.09 |
리액트 Hooks (0) | 2025.01.08 |
[React] 리액트 Hook (훅) (2) | 2024.08.28 |