6주차 부터는 리액트에 대해서 배우기 시작했다. 같은 동작을 구현할 때 자바스크립트 보다 더 쉽게, 간결하게 구현 할 수 있다는 장점이 있지만, 새로운 JSX문법에 대해서도 공부해야 한다. 오늘은 수업시간에 실습과제로 내주신 useRef를 이용한 회원가입 유효성 검사 코드 를 작성해 보았다.
import React, { useRef, useState } from "react";
import "./App.css";
import Effect from "./Effect";
import Memo from "./Memo";
const App = () => {
const inputId = useRef(null); //아이디 입력하는 인풋태그 제어하는 ref
const inputPw = useRef(null); // 패스워드 입력하는 인풋태그 제어하는 ref
const [idValid, setIdValid] = useState(false); // 아이디가 유효성검사 규칙에 어긋나면 경고메시지 띄워주려고 만듬.
const [pwValid, setPwValid] = useState(false); // PW가 유효성검사 규칙에 어긋나면 경고메시지 띄워주려고 만듬.
const [disabled, setDisabled] = useState(false); // 버튼 disabled 하려고 만듬.
const handleClick = () => {
if (inputId.current) {
if (
inputId.current.value.length >= 6 &&
inputId.current.value.length <= 20
) {
setIdValid(false);
if (
inputPw.current.value.length >= 12 &&
inputPw.current.value.length <= 20
) {
setPwValid(false);
alert("회원가입 성공!");
} else {
alert("error!");
setPwValid(true);
inputPw.current.value = "";
inputPw.current.focus();
}
} else {
alert("error!");
setIdValid(true);
inputId.current.value = "";
inputId.current.focus();
}
} else if (inputId.current.value === "" && inputPw.current.value === "") {
setDisabled(true);
}
};
return (
<div>
<div>
<input
type="text"
name="id"
placeholder="6글자 이상 20글자 이하"
ref={inputId}
onChange={(e) => {
if (
e.target.value === "" ||
(e.target.value.length >= 6 && e.target.value.length <= 20)
) {
setIdValid(false);
} else {
setIdValid(true); // 유효하지 않은 id 입니다.
}
}}
/>
{idValid === true ? <span>유효하지 않은 id 입니다.</span> : null}
</div>
<div>
<input
type="text"
name="password"
placeholder="12글자 이상 20글자 이하"
ref={inputPw}
onChange={(e) => {
if (
e.target.value === "" ||
(e.target.value.length >= 12 && e.target.value.length <= 20)
) {
setPwValid(false);
} else {
setPwValid(true);
}
}}
/>
{pwValid === true ? <span>유효하지 않은 pw 입니다.</span> : null}
</div>
<button type="button" onClick={handleClick} disabled={disabled}>
회원가입
</button>
</div>
);
};
export default App;