[ 리액트 / React ] 회원 가입

2025. 4. 18. 09:51·Web Development/React

[ React ] 회원 가입


▶ 회원 가입(Create Read Update Delete) 


   CRUD 중 C(create)에 속한다.

 

▶ 회원 가입 로직 설계


- 회원가입 로직은 다음과 같이 설계하였다.

 

   Request Method: POST
   Body: {"userId": "user01", "userPassword": "pass1234"}

 

  1. Client(React) --Request--> Server(Spring Boot)
    - 클라이언트에서 /adduser로 요청을 보낸다.
       
    이때, Body에는 Id와 Password가 포함된다.

  2. Server --Create(Insert)--> DB
    - 서버는 클라이언트에서 받아온 데이터를 DB에 추가한다.

  3. Server --Response--> Client
    - 서버는 클라이언트에게 성공 여부를 알려준다. ( {"success": true} OR {"success": false} )

  4. 클라이언트는 서버가 알려준 정보를 바탕으로 성공 실패 여부를 사용자에게 알려준다.

∇ 그림으로 간략하게 구현한 로직

더보기

 

▶ 회원 가입 코드 구현 - 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
'Web Development/React' 카테고리의 다른 글
  • [ 리액트 / React ] Redux Toolkit
  • [ 리액트 / React ] props
  • [ 리액트 / React ] 컴포넌트 Component
  • [ 리액트 / React ] State 상태 변수 (ps. Destructing)
apply2y
apply2y
  • apply2y
    apply's blog
    apply2y
  • 전체
    오늘
    어제
    • 분류 전체보기 (27) N
      • Web Project (3) N
        • Project. Typers (3) N
      • Web Development (11)
        • Troubleshooting Note (2)
        • ORM | JPA (1)
        • Spring Boot (1)
        • JWT (1)
        • React (6)
      • Web Security (0)
      • Cloud (3)
        • AWS (3)
      • 리눅스마스터 (6)
        • 리눅스의 개요 (2)
        • 리눅스 시스템의 이해 (2)
        • 네트워크의 이해 (1)
        • 네트워크 보안 (1)
      • Study Notes (2)
      • 마인크래프트 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    variable might not have been initialize
    React
    웹 토큰
    object relation mapping
    AWS
    typers
    리눅스 마스터 1급
    spring boot 시작하기
    spring boot
    객체 관계 매핑
    아마존 웹 서비스
    리눅스 마스터 2급
    spring boot 환경설정
    gh repo clone
    리액트
    토큰 방식
    springboot variable might not have been initialize
    간단
    리눅스 마스터
    jwt이란?
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
apply2y
[ 리액트 / React ] 회원 가입
상단으로

티스토리툴바