🔑난 안피곤하다... 난 안피곤하다...
💡 React Ref 란?
📃 Ref는 Reference의 줄임말로, React 요소 또는 DOM 요소를 참조(Reference)하여 포커스를 설정하거나 특정 요소를 관리할 때 사용됩니다. Ref는 React에서 DOM 요소에 직접 접근하거나 조작해야 할 때 활용됩니다
💻Class 컴포넌트에서 Ref 사용
import { Component, createRef } from "react";
class MyComponent extends Component {
constructor(props) {
super(props);
// Refs를 생성
this.inputRef = createRef();
this.buttonRef = createRef();
this.paragraphRef = createRef();
}
handler = () => {
// input 요소에 포커스
if (this.inputRef.current) {
this.inputRef.current.focus();
}
};
componentDidMount() {
// 초기 렌더링 시 ref로 DOM 요소 접근 확인 (필요 시 삭제 가능)
console.log("Input:", this.inputRef.current);
console.log("Button:", this.buttonRef.current?.textContent); // 버튼 텍스트
console.log("Paragraph:", this.paragraphRef.current);
}
render() {
return (
<>
<input ref={this.inputRef} />
<button ref={this.buttonRef} onClick={this.handler}>
포커스전달
</button>
<p ref={this.paragraphRef}>안녕하세요</p>
</>
);
}
}
export default MyComponent;
⬆️ 특정 입력 필드에 자동으로 포커스를 설정하거나 유저 인터렉션에 따라 동적으로 포커스를 이동시킬 수 있습니다. 또한 console.log를 통해 볼 수 있는 것처럼 DOM 요소의 현재 상태(값, 속성 등)를 즉시 확인하고 반응할 수 있습니다.
💡 Ref를 통해서 회원가입 구현
📃 Ref는 React에서 DOM 요소나 React 요소를 직접 참조하기 위해 사용됩니다. 특히 회원가입 폼이나 입력 폼에서 유용하게 사용됩니다. 사용자가 빈칸을 남겼을 때, 특정 입력 필드에 포커스를 주어 입력을 유도하는 데 효과적입니다.
💻CODE
import React, { Component } from "react";
import "./App.css";
class App extends Component {
state = {
id: "",
password: "",
validPassword: "",
};
// 공통 핸들러로 state 업데이트
inputHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
// 유효성 검사 및 Ref로 focus 관리
validIdPassword = (e) => {
e.preventDefault();
const { id, password, validPassword } = this.state;
if (id.trim() === "") {
alert("아이디를 입력해주세요");
this.myId.focus();
return;
}
if (password === "") {
alert("비밀번호를 입력해주세요");
this.myPassword.focus();
return;
}
if (validPassword === "") {
alert("검증 비밀번호를 입력해주세요");
this.validPassword.focus();
return;
}
if (password !== validPassword) {
alert("비밀번호가 다릅니다");
this.setState({ password: "", validPassword: "" });
this.myPassword.focus();
return;
}
alert("회원 가입 성공입니다");
};
render() {
const { id, password, validPassword } = this.state;
return (
<div style={{ margin: 20 }}>
<form onSubmit={this.validIdPassword}>
<label>
ID :{" "}
<input
type="text"
value={id}
name="id"
onChange={this.inputHandler}
ref={(x) => (this.myId = x)}
placeholder="아이디를 입력해주세요"
/>
</label>
<br />
<label>
PW :{" "}
<input
type="password"
value={password}
name="password"
onChange={this.inputHandler}
ref={(x) => (this.myPassword = x)}
placeholder="비밀번호를 입력해주세요"
/>
</label>
<br />
<label>
PW :{" "}
<input
type="password"
value={validPassword}
name="validPassword"
onChange={this.inputHandler}
ref={(x) => (this.validPassword = x)}
placeholder="비밀번호 재입력"
/>
</label>
<br />
<button type="submit">등록</button>
</form>
</div>
);
}
}
export default App;
1️⃣ state 설정
- id, password, validPassword를 상태로 관리하여 입력 값을 저장합니다.
- inputHandler[계산된 속성명]로 모든 입력 필드를 관리할 수 있도록 설정했습니다.
2️⃣ Ref 활용
- 입력 필드에 빈칸이 있을 경우, Ref를 사용하여 포커스를 특정 요소에 이동시킵니다.
- 이를 통해 사용자에게 입력을 유도합니다.
3️⃣ 유효성 검사
- validIdPassword 함수에서 입력 값 검증을 진행합니다.
- 입력값이 유효하지 않으면 alert로 메시지를 띄우고, Ref로 포커스를 이동합니다.
💡 컴포넌트의 생명주기 Lifecycle
📃 Ref는 Reference의 줄임말로, React 요소 또는 DOM 요소를 참조(Reference)하여 포커스를 설정하거나 특정 요소를 관리할 때 사용됩니다. Ref는 React에서 DOM 요소에 직접 접근하거나 조작해야 할 때 활용됩니다
💻Class 컴포넌트에서 Ref 사용
import React, { Component } from 'react'
import "./LifecycleSample.css"
class LifecycleSample extends Component {
constructor(props) {
super(props);
console.log('constructor: 컴포넌트 생성');
this.state = { count: 0 };
}
// 컴포넌트가 처음 렌더링 된 후 실행
componentDidMount() {
console.log('componentDidMount: 컴포넌트가 마운트 되었습니다');
}
// 컴포넌트가 업데이트 될 때마다 실행
shouldComponentUpdate(nextProps, nextState) {
console.log('shouldComponentUpdate: 업데이트 여부 결정');
return nextState.count % 2 === 0; // 홀수일 때는 업데이트하지 않음
}
// 컴포넌트가 업데이트 된 후 실행
componentDidUpdate(prevProps, prevState) {
console.log('componentDidUpdate: 컴포넌트가 업데이트 되었습니다');
}
// 컴포넌트가 언마운트 되기 전에 실행
componentWillUnmount() {
console.log('componentWillUnmount: 컴포넌트가 언마운트 되기 전에 실행');
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log('render: 생성 주기 컴포넌트 렌더링');
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default LifecycleSample
1️⃣ constructor: 컴포넌트가 생성될 때 count 상태를 초기화합니다
2️⃣ render: React 요소를 반환하여 DOM 화면에 그려질 내용을 반환합니다
3️⃣ componentDidMount: 컴포넌트가 마운트된 후에 호출되어, 초기화 작업을 할 수 있습니다
4️⃣ shouldComponentUpdate: 상태 변경 시, 렌더링 여부를 결정합니다. 여기서는 count가 짝수일 때만 렌더링하도록 설정하였습니다
5️⃣ componentDidUpdate: 상태가 업데이트된 후 호출되며, UI에 반영된 후 추가적인 작업을 할 수 있습니다
6️⃣ componentWillUnmount: 컴포넌트가 제거되기 전에 호출되어, 정리 작업을 할 수 있습니다