WebProgramming/React

[React] 부모 Component -> 자식 Component에게 함수/리스 전달하기

2022. 7. 4. 09:55

이번에는 데이터를 추가해보겠습니다!

App>DiaryList>DiaryItem 부모>자식>손자에게 onDelete함수를 전달하겠습니다.

우선, App에서 DiaryList로 onDelete함수를 props로 전달,전달해주겠습니다.

const App = () => {
  return (
    <div className="App">
      <DiaryList onDelete={onDelete} diaryList={data} />
    </div>
  );
}

DiaryList입니다. onDelete를 props로 전달받아, DiaryItem에게 props로 전달하였습니다.

const DiaryList = ({ diaryList, onDelete }) => {
  return(
    <div>
        {diaryList.map((it)=>(
          <DiaryItem key={it.id}{...it} onDelete = {onDelete} />
        ))}
    </div>
  )
};

DiaryItem입니다. onDelete함수를 props로 전달받아 button의 onClick 이벤트함수로 bind해주었습니다.

if(window.confirm(" "){ }로, alert창을 띄워, 확인을 누르면 { }를 실행합니다.

const DiaryItem = ({
  author,
  content,
  created_date,
  emotion,
  id,
  onDelete,
}) => {
  return(
    <button onClick={() =>{
      console.log(id);
      if(window.confirm(`${id}번째 일기를 정말 삭제하시겠습니까?`)){
      	onDelete(id);
      }
    }
    />
  )
}

다음은 App에서 만든 onDelete함수입니다.

const onDelete = (targetId) => {
  console.log(`${targetId}가 삭제되었습니다.`);
  const newDiaryList = data.filter((it) => it.id !== targetId);
  setData(newDiaryList);
};

targetId를 인수로 전달받습니다. 위에서DiaryItem(id)에서 전달한 매게변수입니다.

새로운 리스트 newDiaryList를 만들어, data.filter((it) => it.id!=targetId); setData(newDiaryList); 로, 전달받은 인수 targetId를 제외한 요소들로 리스트를 재구성해줍니다.

 


오늘은 리스트를 만들어, 부모 Component에서 자식 Component를 전달하여 이를 사용해볼건데요.

우선, 리스트를 부모 Component에 정의해볼게요.

const emotionList = [
  {
    emotion_id: 1,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion1.png`,
    emotion_descript: "완전 좋음",
  },
  {
    emotion_id: 2,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion2.png`,
    emotion_descript: "좋음",
  },
  {
    emotion_id: 3,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion3.png`,
    emotion_descript: "그럭저럭",
  },
  {
    emotion_id: 4,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion4.png`,
    emotion_descript: "나쁨",
  },
  {
    emotion_id: 5,
    emotion_img: process.env.PUBLIC_URL + `/assets/emotion5.png`,
    emotion_descript: "끔찍함",
  },
];

부모 Component 내부입니다. map을 통해 위에서 만든 emotionList를 하나씩 꺼내 it에 집어 넣은 후, key값을 it.emotion_id로    it를 전달해줍니다.

const DiaryEditor = () => {
  return (
    <div className="DiaryEditor">
      <div>
        <section>
          <h4>오늘의 감정</h4>
          <div className="input_box emotion_list_wrapper">
            {emotionList.map((it) => (
              <EmotionItem key={it.emotion_id} {...it} />
            ))}
          </div>
        </section>
      </div>
    </div>
  );
};

자식 Component입니다.

const EmotionItem = ({
  emotion_id,
  emotion_img,
  emotion_descript,
}) => {
  return (
    <div key={emotion_id}>
      <img src={emotion_img} />
      <span>{emotion_descript}</span>
    </div>
  );
};

export default EmotionItem;

props로 전달받은 emotion_id,emotionimg,emotion_descript를 받은 후, key=emotionid, src=emotion_img, 내용=emotion_descript를 해줍니다.

위에서 볼 수 있듯이 props로 내보낼 때와 받을 때 모두 {중괄호}를 사용하여야 합니다.

 

저작자표시 (새창열림)

'WebProgramming > React' 카테고리의 다른 글

[React] useState로 input 상태 관리하기  (0) 2022.07.07
[React] MyButton을 만들어 재활용하기  (0) 2022.07.07
[React] 라우팅(react-router-dom)(useParams, Query)  (0) 2022.07.07
[React] Hook  (0) 2022.07.07
[React] 자식 Component -> 부모 Component로 데이터 전달하기  (0) 2022.07.04
[React] List Rendering  (0) 2022.07.03
[React] useRef를 이용한 DOM조작  (0) 2022.07.03
[React] React 프로젝트 - DiaryEditor Component  (0) 2022.07.01
'WebProgramming/React' 카테고리의 다른 글
  • [React] 라우팅(react-router-dom)(useParams, Query)
  • [React] Hook
  • [React] 자식 Component -> 부모 Component로 데이터 전달하기
  • [React] List Rendering
피터s
피터s
1년차 프론트엔드 개발자입니다 😣 아직 열심히 배우는 중이에요! 리액트를 하고있어요 :) - gueit214@naver.com - https://github.com/gueit214
피터s
피터의 성장기록
피터s
전체
오늘
어제
  • 분류 전체보기 (200)
    • 코딩 테스트 (25)
      • 프로그래머스 (16)
      • LeetCode (8)
      • 백준 (1)
    • 개발 독서 일지 (1)
    • 기업 분석 (4)
    • 개발 일지 (19)
      • 최신기술 도전기 (1)
      • 에러 처리 (5)
      • 개발 일지 (12)
    • 개발 일상 (36)
      • 개발 회고 (22)
      • 개발 이야기 (12)
      • 개발 서적 (1)
    • 취업 관련 지식 (11)
    • 알고리즘 (17)
    • WebProgramming (84)
      • WebProgramming (8)
      • HTML (5)
      • CSS (8)
      • JS (21)
      • React (40)

블로그 메뉴

  • About
  • 2022년 개발 성장기
  • 앞으로의 계획
  • github
  • 일상 blog

공지사항

인기 글

태그

  • 구름톤
  • 개발 일상
  • 1일 1커밋 후기
  • 누적합
  • 구름
  • 함수
  • 카카오
  • 카카오 채용연계형 인턴십
  • Retry
  • 반복문
  • lv3
  • LV2
  • Kakao Tech Internship
  • Union-find
  • 개발 회고
  • 해커톤
  • dfs
  • 1년 회고
  • 스터디 후기
  • 개발 is life
  • BFS
  • KAKAO BLIND

최근 댓글

최근 글

hELLO · Designed By 정상우.
피터s
[React] 부모 Component -> 자식 Component에게 함수/리스 전달하기
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.