DiaryProject(React) - 회원가입 폼(2)

ryan·2022년 4월 25일
0

개선점 체크리스트


이번 게시글에서 다룰 내용 Bold 처리.

1. onChange이벤트가 발생할 때마다 렌더링이 발생
1) state가 아닌 변수 할당으로 해결할 수 있는 지 확인
2. password, passwordCheck input 일치하지 않으면 alert 메세지 출력

3. email input은 email 형태로 작성하게 하기
4. 비밀번호 조건 설정하고 일치하지 않으면 alert 메세지 출력
5. new Date를 통해 고유 id 부여하기 (또는 date, 이메일, 닉네임의 조합)
6. input이 하나라도 빈 값(undefined)로 출력되면 setState 안되게 하기.

  • 위의 input 조건 충족안될 시 setState 안되게 하기

import React, {useState, memo, useRef} from 'react';
import './sign.css';

const SignUp = memo(() => {
  const [userData, setUserData] = useState([]);
  // input 변수를 state에서 Ref로 바꿨음.
  // input에서 수정이 일어나도 setState가 되지 않기 때문에
  // 불필요한 렌더링을 없앨 수 있음.
  const emailValue = useRef();
  const nameValue = useRef();
  const passwordValue = useRef();
  const pwCheckValue = useRef();
  const onChangeName = (e) => {
    nameValue.current = e.target.value;
  };
  const onChangeEmail = (e) => {
    emailValue.current = e.target.value;
  };
  const onChangePw = (e) => {
    passwordValue.current = e.target.value;
  };
  const onChangePwCk = (e) => {
    pwCheckValue.current = e.target.value;
  };
  const onSubmit = (e) => {
    e.preventDefault();
    setUserData((prevUserData) => {
      return [
        ...prevUserData,
        {
          name: nameValue,
          email: emailValue,
          pw: passwordValue,
          pwCk: pwCheckValue,
        },
      ];
    });
  };
  const checkPw = () => { 
    // ref.current value를 비교 
    // 비밀번호-비밀번호확인 불일치 시 alert 태그 return 
    return pwCheckValue.current === passwordValue.current ? null : (
      <>
        <span className='formAlert'>비밀번호가 일치하지 않습니다.</span>
      </>
    );
  };
  const checkEmail = () => {
    // 정규표현식으로 이메일 유효성 검사 진행 
    // input type email의 경우 css 커스터마이징 문제 발생
    // false일 경우, alert 태그 return 
    const reg = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
    return reg.test(emailValue.current) ? null : (
      <>
        <span className='formAlert'>이메일 형식에 맞게 입력해주세요.</span>
      </>
    );
  };

  return (
    <>
      <div className='formDiv'>
        <h1>회원가입</h1>
        <form onSubmit={onSubmit} className='formTag'>
          <div className='inputContainer'>
            <label htmlFor='nameInput'>이름</label>
            <input type='text' id='nameInput' onChange={onChangeName} onSubmit={checkEmail} />
          </div>
          <div className='inputContainer'>
            <label htmlFor='emailInput'>이메일</label>
            <input type='text' id='emailInput' required autoFocus onChange={onChangeEmail} />
            {checkEmail()}
          </div>
          <div className='inputContainer'>
            <label htmlFor='pwInput'>비밀번호</label>
            <input type='text' id='pwInput' onChange={onChangePw} />
            <span>비밀번호는 8~15자리 문자와 숫자</span>
          </div>
          <div className='inputContainer'>
            <label htmlFor='pwCkInput'>비밀번호 확인</label>
            <input type='text' id='pwCkInput' onChange={onChangePwCk} />
            {checkPw()}
          </div>
          <button>회원가입 완료!</button>
        </form>
      </div>
    </>
  );
});

export default SignUp;

개선점

  1. new Date를 통해 고유 id 부여하기 (또는 date, 이메일, 닉네임의 조합)
  2. input이 하나라도 빈 값(undefined)로 출력되면 setState 안되게 하기.
  3. 한가지라도 input 조건 충족 안될 시 setState 취소

고민하고 있는 부분

  1. 현재는 회원가입 폼 유효성 검사가 submit시에만 이뤄지게 되어있음. input onChange 이벤트를 통해 실시간으로 유효성 검사를 진행하고 싶음. > 실시간 유효성 검사를 state를 안쓰고 할 수 있는지 의문.
  2. onChangeName~onChangePwCk 비슷한 코드 중복이 발생하는데 중복 없애고 싶다.
  3. 비동기 함수를 통해 데이터 전송 로직 만들어야 함.(await/async 학습 필요)

개선점 프로그래밍 아이디어 아카이빙

  1. Sign 컴포넌트 내 clickable 변수로 선언하고 onChangeName~onChangePwCk 내 ref.current value로 유효성 검사 실시간으로 진행 submit 함수 내에 clickable=false일 경우, setState가 아닌 Alert(window.alert x) 메서드 작성
  2. 코드 길어지면 분리도 생각해야 함.
  3. 유효성 검사 일치하지 않으면 알림 문구 띄워줘야 하는데 이벤트 발생 태그가 아닌 별도의 div태그에서 어떻게 띄울건지 생각해야 함
profile
프론트엔드 개발자

0개의 댓글