IT_World
[React] Login / Password 본문
password button 불 들어오기
완성 코드
mport styles from './Login.module.scss';
import { Link, useNavigate } from 'react-router-dom';
import { useState } from 'react';
function Login() {
const navigate = useNavigate();
const [idValue, setIdValue] = useState('');
const [password, setPassword] = useState('');
const [disable, setDisable] = useState(true);
const [opacity, setOpacity] = useState(0.5);
const goToList = () => {
navigate('/main-geunhongLim');
};
const handleInput = event => {
return event.target.value;
};
return (
<section className={styles.loginBox}>
<figure className={styles.ghLogo}>
<img src="images/logo.png" alt="logo" />
</figure>
<div className={styles.loginFormBox}>
<input
type="text"
placeholder="전화번호, 사용자 이름 또는 이메일"
onChange={event => {
setIdValue(handleInput(event));
console.log(idValue);}}/>
<input
type="password"
placeholder="비밀번호"
onChange={event => {
setPassword(handleInput(event));}}/>
<button>
로그인
</button>
</div>
<div className={styles.lostPasswordBox}>
<Link to="/" className={styles.ghLink}>
비밀번호를 잊으셨나요?
</Link>
</div>
</section>
);
}
export default Login;
버튼에 불 들어오기
이제 필요한 것은 로그인 버튼에 불이 들어오게 하는 것이다.
조건 :
아이디에 '@'가 포함, 비밀번호가 5자리 이상
정규식도 가능하지만 아래처럼 간단하게 작성해본다.
idValue.includes('@') && password.lengh >= 5
이제 중요한 것은 button에게 이 조건을 알려주는 방법이다.
버튼의 속성들을 추가해야한다.
- disable : 버튼 비활성화
- opacity : 불투명도
<button
disable = {}
style = {{opacity: }}
> 로그인 </button>
내가 버튼에게 주고 싶은 것은 아래와 같다.
조건에 맞으면 버튼을 활성화 시켜줘 (false)
조건에 맞으면 버튼의 opacity를 1로 만들어줘
state를 쓰면 초기값도 정할 수 있고 값도 갱신할 수 있지 않은가? 사용해주겠다.
function Login() {
const navigate = useNavigate();
const [idValue, setIdValue] = useState('');
const [password, setPassword] = useState('');
const [disable, setDisable] = useState(true);
const [opacity, setOpacity] = useState(0.5);
그리고 이 조건들에 대한 각각의 함수를 만들어주겠다. (이번엔 clean code의 가르침을 따르겠다.)
const handleopacity = () => {
idValue.includes('@') && password.length >= 5
? setOpacity(1)
: setOpacity(0.5);
};
const handleDisable = () => {
idValue.includes('@') && password.length >= 5
? setDisable(false)
: setDisable(true);
};
삼항연산자로 처리했다. 그리고 버튼의 속성들에게도 변수를 전달해줬다.
<button
disable = {disable}
style = {{opacity: opacity}}
> 로그인 </button>
자. 이제 이걸 어디에다가 넣냐가 문제다... 이 함수는 언제 가동되어야할까?
참고로 아이디와 비밀번호에 값이 변할 때마다 조건에 맞는지 계속 확인해줘야한다.
그러므로 이 함수들은 아이디, 비밀번호 이벤트에 들어가야한다.
<input
type="text"
placeholder="전화번호, 사용자 이름 또는 이메일"
onChange={event => {
setIdValue(handleInput(event));
console.log(idValue);
handleopacity();
handleDisable();
}}
/>
<input
type="password"
placeholder="비밀번호"
onChange={event => {
setPassword(handleInput(event));
handleopacity();
handleDisable();
}}
/>
버튼을 누르면 List페이지로 이동하게 해보았다.
<button
disabled={disable}
style={{
opacity: opacity,
}}
onClick={event => {
goToList();
}}
>
'Front-End > React' 카테고리의 다른 글
[React] 함수형 컴포넌트 (0) | 2022.04.14 |
---|---|
[React] Signin form validation check 적용 (0) | 2022.04.14 |
[React] Webhook (0) | 2022.04.12 |
[React] event system (0) | 2022.04.08 |
[React] Checkbox (0) | 2022.04.06 |
Comments