[ React ] 회원 가입
▶ 회원 가입(Create Read Update Delete)
CRUD 중 C(create)에 속한다.
▶ 회원 가입 로직 설계
- 회원가입 로직은 다음과 같이 설계하였다.
Request Method: POST
Body: {"userId": "user01", "userPassword": "pass1234"}
- Client(React) --Request--> Server(Spring Boot)
- 클라이언트에서 /adduser로 요청을 보낸다.
이때, Body에는 Id와 Password가 포함된다. - Server --Create(Insert)--> DB
- 서버는 클라이언트에서 받아온 데이터를 DB에 추가한다. - Server --Response--> Client
- 서버는 클라이언트에게 성공 여부를 알려준다. ( {"success": true} OR {"success": false} ) - 클라이언트는 서버가 알려준 정보를 바탕으로 성공 실패 여부를 사용자에게 알려준다.
∇ 그림으로 간략하게 구현한 로직
▶ 회원 가입 코드 구현 - React(Client)
∇ [ handleSubmit 구문 ]
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post("http://localhost:8080/adduser", {
userId: id,
userPassword: password
});
console.log("서버 응답:", response.data);
alert("계정 생성 완료!");
fechUser();
} catch (error) {
console.error("에러 발생:", error);
alert("계정 생성 실패");
}
};
∇ [ Form 구문 ]
<form onSubmit={handleSubmit}>
<div className="title">Create Account</div>
<div className="contents">
<label htmlFor="id" style={{fontSize: '30px'}}>ID</label>
<input
name='id'
value={id}
onChange={(e) => setId(e.target.value)}
></input>
<label htmlFor="Password" style={{fontSize: '30px'}}>Password</label>
<input
name='password'
value={password}
onChange={(e) => setPassword(e.target.value)}
></input>
<input className='btn' type='submit' value={"Create Account"}></input>
<br></br>
<br></br>
<br></br>
<h2>or</h2>
<a onClick={()=>{alert("hello")}}><h1 className='kakao'>Kakao</h1></a>
</div>
</form>
∇ [ State(상태) 구문 ]
const [id, setId] = useState('')
const [password, setPassword] = useState('')
▷ 주요 구문 설명
<form onSubmit={handleSubmit}
「코드 해석」
→ 폼(form)이 제출(submit)됐을 때, handleSubmit 함수를 실행시킨다.
「onSubmit」
→ 폼(form)이 제출(submit)됐을 때, {} 안에 있는 함수를 실행시킨다.
<input>
name='id'
value={id}
onChange={(e) => setId(e.target.value)}
></input>
→ 제어 컴포넌트로써, input 필드에 입력되는 값이 상태 변수 id에 저장된다.
또한, 폼 제출 시 이 input의 값의 Key는 'id'로 전달된다.
「value={id}」
→ 입력값이 상태 변수 id와 동기화되는 Controlled Component(제어 컴포넌트)로 만들어준다.
「onChange={(e) => setId(e.target.value)}」
→ 입력값이 바뀔 때마다 id 상태를 실시간 업데이트한다.
「name='id'」
→ name의 값은 폼 전송 시 해당 입력 필드의 Key 값으로 사용된다.
「Controlled Component」 란?
→ React의 상태(state)가 input, textarea, select 같은 폼 요소의 값을 제어하는 컴포넌트를 말한다.
즉, 입력값을 React의 상태로 관리하는 방식이다.
// handleSubmit 함수
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post("http://localhost:8080/adduser", {
userId: id,
userPassword: password
});
console.log("서버 응답:", response.data);
alert("계정 생성 완료!");
} catch (error) {
console.error("에러 발생:", error);
alert("계정 생성 실패");
}};
「코드 해석」
→ 서버(localhost:8080)에 /adduser경로로 비동기 POST 요청을 보낸 후,
응답받은 값에 따라 성공 실패 여부를 사용자에게 알려준다.
「e.preventDefault()」
→ 폼의 제출 시 새로고침을 방지한다.
「const response = await axios.post("http ... ", {
userId: id,
userPassword: password
});」
→ 1. 서버에게 {}안 데이터를 바탕으로 비동기 POST 요청을 진행한다.
2. POST 요청의 반환 값을 const response에 저장한다.
「response.data」
→ 서버의 반환 값 데이터를 리턴한다.
'Web Development > React' 카테고리의 다른 글
[ 리액트 / React ] Redux Toolkit (0) | 2025.03.20 |
---|---|
[ 리액트 / React ] props (0) | 2025.03.19 |
[ 리액트 / React ] 컴포넌트 Component (0) | 2025.03.18 |
[ 리액트 / React ] State 상태 변수 (ps. Destructing) (0) | 2025.03.17 |
[ 리액트 / React ] React를 사용하는 이유 - SPA (2) | 2025.03.15 |