Tech/React

[React] 고객 추가 양식(form) 구현 및 이벤트 핸들링

lonnie(동현) 2021. 3. 17. 15:10

🍕 고객 추가 form 구현 및 이벤트 핸들링

0️⃣ CustomerAdd.js 컴포넌트 만들기 (./client/src/CustomerAdd.js)

1️⃣ 서버와의 통신 목적 라이브러리인 axios 설치하기

directory를 client로 이동한 뒤 npm install --save axios 명령어를 통해서 axios를 설치한다.

2️⃣ CustomerAdd.js 컴포넌트 작성하기 (./client/src/CustomerAdd.js)

1) React 라이브러리를 불러오고, post방식으로 고객 추가 데이터를 서버로 보낼 수 있도록 axios에서 post 라이브러리를 불러온다.

import React from 'react';
import { post } form 'axios';

2) 필요한 state 값들을 초기화시켜준다.

class CustomerAdd extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            file     : null, 
            userName : '',
            birthday : '',
            gender   : '',
            job      : '',
            fileName : ''
        }
    }
}

3) 고객 추가 form을 정의해주고, form을 전송하는 함수를 설정해준다.
(1) handlerFileChange : 사용자가 파일을 업로드해서 보낼 준비가 되었을 때 처리 결과를 사용자에게 보여주기 위해서 사용
(2) handlerValueChange : 사용자가 값을 입력했을 때 그러한 이벤트를 처리하기 위해서 사용

render(){
        return(

            <form onSubmit = {this.handleFormSubmit}>
                <h1> 고객 추가 </h1>
                    프로필 이미지 : <input type  = "file" name  = "file" file  = {this.state.file} value  = {this.state.fileName} onChange  = {this.handleFileChange}/><br/>
                    이름 : <input type  = "text" name  = "userName" value  = {this.state.userName} onChange  = {this.handleValueChange}/><br/> 
                    생년월일 : <input type = "text" name = "birthday" value = {this.state.birthday} onChange = {this.handleValueChange}/><br/>
                    성별: <input type = "text" name = "gender" value = {this.state.gender} onChange = {this.handleValueChange}/><br/>
                    직업 : <input type = "text" name = "job" value = {this.state.job} onChange = {this.handleValueChange}/><br/>
                    <button type = "submit">추가하기</button>
            </form>
        ) // return
    } // render

4) addCustomer 모듈 만들기
(1) '/api/customers'로 데이터를 보낼 수 있도록 만든다.
(2) 'formData'라는 객체를 통해서 데이터를 전달해 줄 수 있도록 한다.
(3) 파일이 포함된 데이터를 전송할 때는 웹 표준에 맞는 header인 'multipart/form-data'를 추가해주어야 한다.
(4) axios의 post를 이용하여 해당 url에 formData를 환경 설정에 맞게 서버로 데이터를 보낼 수 있도록 해준다.

addCustomer = () => {
    const url = '/api/customers';
    const formData = new FormData();
    formData.append('image',this.state.file);
    formData.append('name',this.state.userName);
    formData.append('birthday',this.state.birthday);
    formData.append('gender',this.state.gender);
    formData.append('job',this.state.job);
    const config = {
         headers : {
            'content-type' : 'mutipart/form-data'
        }
    } // config
    return post(url, formData, config);
} // addCustomer

5) handleFormSubmit 함수 만들기
(1) 내부적으로 'e'변수를 전달받는다.
(2) 'preventDefault()' : 데이터가 서버로 전달될 때 오류가 발생하지 않도록 하는 함수
(3) 'addCustomer()' 불러오기
(4)'then'을 이용해서 서버로부터 'response'가 왔을 때, 데이터를 콘솔에 출력

handleFormSubmit = (e) => {
  e.preventDefault()
  this.addCustomer()
      .then((response) => {
          console.log(response.data);
      })
}

6) handleFileChange 함수 만들기
(1) 'setState'를 통해서 state에 있는 file 값을 변경
(2)'e.target'은 실제로 이벤트가 발생한 input 값 자체를 의미
(3)'e.target.files'는 input 값 자체의 파일을 의미
(4)'e.target.value'는 사용자가 입력 값으로 넣은 파일명

    handleFileChange = (e) => {
        this.setState({
            file : e.target.files[0],
            fileName : e.target.value
        })
    }

7) handleValueChange 함수 만들기
(1) 사용자가 입력한 변경된 값을 'username state'에 실제로 반영을 하겠다는 의미
(2) 'nextState'를 통해 현재 'state'값을 갱신

handleValueChange = (e) => {
    let nextState = {};
    nextState[e.target.name] = e.target.value;
    this.setState(nextState);
}

3️⃣ App.js 에 CustomerAdd 컴포넌트 추가하고 서버 실행해보기 (./client/App.js)

그림과 같이 정상적으로 잘 들어간 것을 확인할 수 있다.

4️⃣ 마무리

고객 추가 form을 구현해서 실제로 클라이언트에서 서버로 데이터를 구현하는 것까지 구현해보았다. 다음에는 express 서버 개발을 통해서 파일 업로드 요청을 처리해서 DB에 데이터를 넣는 작업을 진행해보겠다.

728x90
반응형