타입스크립트로 함께하는 웹 풀 사이클 개발(React, Node.js)/TIL

데브코스 12주차 Day5 - [mini diary] 조건문, 반복문 in react

슈크림 붕어빵 2024. 2. 15. 21:38

조건문

리액트의 html영역 안에서는 if ~else문을 사용할 수 없다.

삼항연산자의 사용은 가능하다.

{post.detail === true ? <Detail post={post}></Detail> : null}

 

반복문

리액트에서 jsx안에서는 for문을 사용할 수 없다.

map을 사용하면 된다.


            {post.map((post, idx) => {
              return (
                <div className="post" key={idx}>
                  <div className="post-head">
                    <div className="post-left">
                      <p>{post.date}</p>
                      <div>
                        <span
                          className="post-title"
                          onClick={() => {
                            handleDetail(idx);
                          }}
                        >
                          {post.title}{" "}
                        </span>
                        <span
                          onClick={() => {
                            handleLike(idx);
                          }}
                        >
                          👍
                        </span>
                        {post.like}
                      </div>
                    </div>
                    <div className="post-right">
                      <button
                        className="delButton"
                        onClick={() => {
                          handleDelete(idx);
                        }}
                      >
                        삭제
                      </button>
                    </div>
                  </div>

                  {post.detail === true ? <Detail post={post}></Detail> : null}
                </div>
              );
            })}

 

post 배열에 데이터 추가하기

const handleSubmit = (title: string, content: string): void => {
    let today = new Date();
    let todayDate = `${today.getFullYear()}-${today.getMonth()}-${today.getDate()}`;
    let newPost: Post = {
      id: post[post.length - 1].id + 1,
      title: title,
      content: content,
      date: todayDate,
      like: 0,
      detail: false,
    };
    setPost((prev) => [...prev, newPost]);
    setInputTitle("");
    setInputContent("");
  };

 

=> 입력된 title, content와 오늘 날짜를 가공하여 배열에 추가한다.

 

 

post 배열에서 삭제하기 - splice

splice (start, deleteCount, item1, item2 ... ) //(삭제시작할 index, 삭제할 개수, 추가할 요소)

 

splice(0,1) => 첫번째 게시물 삭제

splice(1,1) => 두번째 게시물 삭제

splice(2,1) => 세번째 게시물 삭제

 

  const handleDelete = (idx: number) => {
    let cpPost = [...post];
    cpPost.splice(idx, 1);
    setPost(cpPost);
  };

 

=> 선택된 idx를 가진 post를 삭제한다.

기능 구현

1. post 추가

2. post 삭제

3. post 조회 

4. 좋아요 기능