[Project] Hobbyt - map() 사용해서 자식 컴포넌트에 props 2개 내려주는 법

Heera1·2023년 1월 16일
0

[Project] Hobbyt

목록 보기
4/6

개인홈 페이지에 내가 쓴 댓글 리스트를 뽑는 와중에 생긴 에러 처리 방법입니다.
api가 아직 준비되지 않아 프론트에서 테스트를 해 보기 위해 아래와 같이 진행하였습니다.

item의 id 값을 보내는 이유?

item 데이터의 유티크한 id 값만 자식 컴포넌트에서 필요했습니다.
id 값을 자식 컴포넌트에서 patchdelete api 요청을 할 때 url에 함께 추가해야하는 ${id} 값으로 사용할 생각입니다.

어떤 에러가 발생했는지?

자식 컴포넌트에서 props로 받아오는 item가 빈값으로 들어오고 있었다.

해결 방법

  • map() 메소드를 사용해 리스트 배열을 뿌려줍니다.
  • 배열의 interface도 설정해줍니다.
// 부모 컴포넌트
// My CommentList.tsx 파일

interface CommentType {
  title: string;
  id: number;
  content: string;
}

export default function MyCommentList(): React.ReactElement {
  const commentList: CommentType[] = [
    {
      title: "댓글 남겼던 게시글 제목",
      id: 1,
      content:
        "내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용",
    },
    {
      title: "댓글 남겼던 게시글 제목2",
      id: 2,
      content:
        "내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용 내가 작성한 댓글 내용",
    },
  ];
  
  return (
    <CommentContainer>
      {commentList.map((item, index) => {
        console.log(`data.map`, item);
        return (
          <div key={index}>
			// 생략
              <ThreeDotsBox item={item.id} key={index}>
                댓글
              </ThreeDotsBox>
  • props를 받을 자식 컴포넌트는 ThreeDotsBox 입니다. 보다시피 childrenprops를 모두 받고 있는 상황입니다. 이런 경우, 객체 디스트럭쳐링 방식을 사용해 아래와 같이 사용해야 한다. (참고)

// 자식 컴포넌트
// ThreeDotsBox.tsx 파일

export default function ThreeDotsBox({
  children,
  item,
}: {
  children: React.ReactNode;
  item: number;
}) {
  // 생략
  return (
    <div className="">
      <button onClick={onClickHandler} value={item}>
        <BsThreeDots className="cursor-pointer" size={25} color="#d6d6d6" />
      </button>
      {onClick && (
        <SelectBox>
          <button
            className="flex text-center"
            onClick={submitEditHandler}
            value={item}
          >
            {children} 수정
            <BsFillFileEarmarkFill className="mt-1 ml-10" />
          </button>
          <hr className="my-2" />
          <div className="flex text-center">
            {children} 삭제
            <BsFillTrashFill className="mt-1 ml-10" />
          </div>
        </SelectBox>
      )}
    </div>

문제가 됐던 부분

  • 자식 컴포넌트 매개변수 부분에 children 이라고 적었어야 했는데 props라 적었다...
  • 객체 두 개가 자식 컴포넌트에 전달된 상황인데 객체 디스트럭쳐링 방식으로 시도하지 않았다.
profile
웹 개발자

0개의 댓글