Westagram - 1.login page [React]

15699 단어 ReactclonecodingReact

# 🌈 Instagram clone코딩을 해보았다.

🌀 login page를 처음 html/css/javascript로 만들었었다. 그걸 react로 코드를 변형시켜서 만들어 보았다.

(이미지나 구성은 똑같아서 사진은 생략합니당 )

import React, { Component } from 'react';
import './Login.scss';

class LoginJihoo extends React.Component {
  constructor() {
    super();
    this.state = {
      id: '',
      password: '',
    };
  }

  // goToMain = () => {
  //   this.props.history.push('/main-jihoo');
  // };

  submitLoginInfo = () => {
    // console.log('함수호출 성공');
    fetch('http://10.58.0.69:8000/user/signin', {
      method: 'POST',
      body: JSON.stringify({
        // => 프론트에서 백으로 정보를 주는것
        email: this.state.id,
        password: this.state.password,
      }),
    })
      .then(res => res.json()) //자바스크립트로 바꿔준다.
      .then(result => {
        // const { history } = this.props;  //history는 자바스크립트에서 사용할 ㅁ
        if (result.message === 'INVALID_USER') {
          // 맞지 않는 유저
          alert('다시 로그인해주세요');
        } else if (result.access_token) {
          localStorage.setItem('token', result.access_token);
          this.props.history.push('/main-jihoo');
        }
      });
  };

  handleIdInput = e => {
    //IdInput은 event의 약자 e를 인자로 받음
    this.setState({
      id: e.target.value, // console.log-> setState이후라고 다 실행된것은 아니다. 그래서 render밑에서 console.log
    });
  };

  handlePwInput = e => {
    this.setState({
      password: e.target.value,
    });
  };

  render() {
    const okayId = this.state.id.indexOf('@');
    const okayPw = this.state.password.length > 5;
    return (
      <section className="login">
        <h2 className="login-title">WESTAGRAM</h2>
        <div className="input-container">
          <div className="input-wrap">
            <input
              id="id"
              type="text"
              placeholder="전화번호,사용자이름 또는 이메일"
              onChange={this.handleIdInput}
            />
            <input
              id="password"
              type="password"
              placeholder="비밀번호"
              onChange={this.handlePwInput} // 변수를 선언한 경우에는 인자를 선언해야되지만, event시 onchange,
              //onclick자체에 기본값으로 인자가 설정되어 있기 때문에 사용 하지 않아도 상관 없다.
            />
          </div>
          <button
            className={
              okayId !== -1 && okayPw
                ? 'changeButtonColor btn'
                : 'normalButtonColor btn'
              // css 파일로 다시 정하기.
              //validation ? "able" : "disable"
            }
            onClick={this.submitLoginInfo}
            disabled={!(okayId !== -1 && okayPw)}
          >
            로그인
          </button>
        </div>
        <div className="last">
          <p>
            <a href="/">비밀번호를 잊으셨나요?</a>
          </p>
        </div>
      </section>
    );
  }
}

export default LoginJihoo;

👉 state에서 데이터를 저장해서 관리한다.

👉 state에서 저장한 데이터를 handleIdInput에서 setState를 사용해서 데이터를 변경하고(event)를 사용해서 input값에 넣을 수 있게 함수를 짰다.

👉 react로 페이지를 구성한 다음에 백엔드와 통신을 해서 회원가입/로그인이 되는지 확인해보았다.
👉 백엔드와 통신할 때는 fetch를 사용해서 서버주소를 받아오고 프론트에서도 정보를 주고 받아야 하기 때문에 post를 사용한다는 것을 알게 되었다.
👉 그런다음 회원가입을 한 유저인지 아닌지를 판단해서 로그인 여부를 성공해야되기 때문에 token값으로 확인할 수 있는 로직을 짜 보았다.

좋은 웹페이지 즐겨찾기