React
Controlled components와 Uncontrolled components
heeyeonjeong
2021. 2. 17. 23:53
반응형
Controlled components (useState)
import React, { useState } from "react";
export default function App() {
const [inputValue, setInputValue] = useState("");
const handleInputChange = (e) => {
setInputValue(e.target.value)
}
const handleSubmitButton = () => {
alert(inputValue);
};
return (
<div className="App">
<input value={inputValue} onChange={handleInputChange} />
<input type="submit" value="submit" onClick={handleSubmitButton} />
</div>
);
}
Uncontrolled components (useRef)
import React, { useRef } from "react";
export default function App() {
const inputRef = useRef(null);
const handleSubmitButton = () => {
alert(inputRef.current.value);
};
return (
<div className="App">
<input type="text" ref={inputRef} />
<input type="submit" value="submit" onClick={handleSubmitButton} />
</div>
);
}
아래와 같을 때 controlled component 사용
- 유효한 문자인지 확인하기 위해 입력 할 때 항상 입력 값을 알아야하는 양식 유효성 검사
- 신용 카드 입력과 같은 특정 형식이있는 경우
그러나 그 중 어느 것도 필요하지 않고 Uncontrolled components이 더 간단 할 것이라고 생각한다면 Uncontrolled components 사용하기!
Controlled and Uncontrolled components in React!
difference between controlled and uncontrolled components in react
medium.com