☑️React - 로그인/댓글 기능 구현

유자탱자🍋·2021년 3월 9일
2

로그인 기능 구현

📌 구현하고자 하는 기능: id는 @를 포함하고 pw는 5자리 이상일 경우, 로그인 버튼 활성화


step 1.

우선 변하는 값인 id&pw input 값을 state로 선언한다. 이때 loginId, loginPw key 값은 빈 string으로 준다.(초기화)

constructor(){
        super();
        this.state = {
            loginId : " ",
            loginPw : " ",
        };
    }

step 2.

사용자가 id와 pw를 입력할때 state 값을 바꾸기 위해서 setState 함수를 활용한다.
여기서 처음에는 handleInput 함수를 id,pw 각각 두 가지 함수로 분리했는데, name이라는 속성을 부여해 하나로 합쳐줄 수 있다.

handleInput = (e) => {
        this.setState({
            [e.target.name] : e.target.value,
        })
    }
...
<input onChange={this.handleInput} name="loginId" className="inputBox" type="email" placeholder="전화번호, 사용자 이름 또는 이메일" />
<input onChange={this.handleInput} name="loginPw" className="inputBox" type="password" placeholder="비밀번호" />   

step 3.

그 다음 원하는 조건을 변수로 선언해주었다. 두 가지 조건이 모두 충족되어야 하기 때문에 && 을 사용했다.
return 전에 변수로 선언하는 구조는 앞으로도 많이 쓰일 것 같아 기억해두자!⭐️

render() {
const validation = this.state.loginId.includes("@") && this.state.loginPw.length > 4
	return ( ... );
}

step 4.

default 상태일 때는 로그인 버튼의 투명도가 0.5이지만, 주어진 조건을 충족하면 버튼의 투명도가 1이 되어 시각적으로도 활성화되는 기능을 구현하고 싶다. 그래서 inline style으로 opacity를 지정하고, 삼항 연산자를 통해 만약 변수 validation이 true이면 투명도가 1이 되도록 로직을 구현했다.

<button style={{opacity: validation? "1" : "0.5"}}>로그인</button>



댓글 기능 구현

📌 구현하고자 하는 기능: 댓글을 input에 입력하면 list 태그에 댓글 추가


step 1.

로그인 기능과 동일하게 state 값을 선언하였다. 여기서 사용자가 입력하는 input 값은 comment key로, 댓글들이 담겨있는 배열은 commentList key로 지정하였다. 댓글을 입력했을 때, setState 함수를 통해 comment key의 value를 변경해준다.

constructor(){
        super();
        this.state={
            comment : "",
            commentList : [],
        }
    }
...
handleComment = (e) => {
        this.setState({
            comment : e.target.value
        }) 
    }
...
<input onChange={this.handleComment} value={this.state.comment} placeholder="댓글 달기..." />

step 2.

댓글이 추가되는 부분을 하나의 컴포넌트로 분리한다.

lass CommentList extends Component {
    render() {
        return (
            <ul className="commentul" >
                {this.props.commentList.map(list => (
                    <li key={list.id}> <b>im_just_twentyseven</b> {list.comment} </li>
                ))}
            </ul>
        );
    }
}

여기에서 key는 React가 어떤 아이템이 바뀌었는지, 혹은 추가되었는지, 혹은 삭제되었는지를 인식하는데 도움을 준다.요소에 안정적인 ID를 제공하려면 배열 내부 요소에 키를 주어야한다. [출처_리액트 공식 문서]

크게 본다면 map 메소드를 통해 새로운 배열을 반환하게 되는데, 주어진 배열은 부모 컴포넌트의 state 중 commentList이기 때문에 this.props.commentList로 작성하였다.


step 3.

버튼을 클릭했을 때 onClick event가 발생하고, handleList 함수가 실행되도록 한다.
onClick={this.handleList}

handleList 함수에서 핵심은 commentList state 배열에 담길 값을 선언하는 것이다. 리스트를 만들때 필요한 key 값을 위해 현재 시각을 id로 주었다.

const newComment = {
            comment : this.state.comment,
            id : Date.now() 
        };

그리고 setState 함수를 통해 state를 변경하였다. 버튼을 클릭하면 input에 담겨있던 댓글을 다시 없어져야 하기 때문에 comment를 빈 string으로 다시 선언해주었다.

handleList = () => {
   if(this.state.comment.length === 0){
      return;
     }
...
   const newComment = {
      comment : this.state.comment,
      id : Date.now() 
    };
...
   this.setState(state => ({
      commentList : state.commentList.concat(newComment),
      comment : ""
   }))
}

그럼 결국 변수 newComment의 id값은 li 태그의 key값으로, 입력한 comment는 콘텐츠로 들어가게 되는 것이다.




아직 리액트의 event와 state&props 개념이 명확하게 자리 잡지 않아, 그 흐름이 완벽하게 숙지된 것 같지는 않다... 하지만, 부모-자식 컴포넌트, 그리고 Array.map 메소드를 경험할 수 있는 좋은 예시인 것 같아 기록해둔다👩‍💻

그리고 시간이 될 때 리액트 공식 문서에서 리스트와 key 파트 더 자세히 알아보도록 하자!


📌 아직 코린이인 저에게 수정 댓글은 큰 도움이 되니 맘껏 달아주세요! 📌

0개의 댓글