본문 바로가기

React/Mini Projects

Birthday Reminder (useState - Array 사용 기본)

이 포스팅은 Udemy에 올라온 John Smilga의 " React Tutorial and Projects Course" 강의에서 도움을 받았습니다.

강의 속 프로젝트들을 먼저 만들어 본 후에 강의를 듣고 새로 배운 내용이나 실수들을 메모한 것입니다.

https://www.udemy.com/course/react-tutorial-and-projects-course/

 

React Tutorial and Projects Course

Step by Step Learn React.js and Create Interesting Projects

www.udemy.com

 

 

 

 

 

 

 

 

useState를 이용한 가장 기본 프로젝트.

state에 obejets를 담은 Array가 들어가는 경우.

 

 

data.js

export default [
	{
		id: 1,
		name: "Bertie Yates",
		age: 29,
		image: "https://res.cloudinary.com/diqqf3eq2/image/upload/v1595959131/person-2_ipcjws.jpg",
	},
	{
		id: 2,
		name: "Hester Hogan",
		age: 32,
		image: "https://res.cloudinary.com/diqqf3eq2/image/upload/v1595959131/person-3_rxtqvi.jpg",
	},
	{
		id: 3,
		name: "Larry Little",
		age: 36,
		image: "https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883423/person-4_t9nxjt.jpg",
	},
	{
		id: 4,
		name: "Sean Walsh",
		age: 34,
		image: "https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883417/person-3_ipa0mj.jpg",
	},
	{
		id: 5,
		name: "Lola Gardner",
		age: 29,
		image: "https://res.cloudinary.com/diqqf3eq2/image/upload/v1586883334/person-1_rfzshl.jpg",
	},
];

 

 

 

 

 

 

App.js

import { useState } from "react";
import data from "./data";
import List from "./List";

function App() {
	const [people, setPeople] = useState(data);
	return (
		<main>
			<section className="container">
				<h3>{people.length} birthday today</h3>
				<List people={people} />
				<button onClick={() => setPeople([])}>Clear all</button>
			</section>
		</main>
	);
}

export default App;

 

1. 리스트 사람 숫자는 배열의 길이 -> {people.length} 

2. List 컴포넌트에 people data를 넣어줌. 

- 하위 List 컴포넌트에서 people data를 받아와서 거기서만 사용했다면 App.js에서 생일인 사람의 숫자나 Clear all버튼 작동하기 힘들었을 것. 상위 컴포넌트에서 props를 이용해서 하위 컴포넌트로 데이터를 전해주는 방식이 옳다.

3. Clear All 버튼은 사실 쉽다. people state 속 배열을 텅 빈 배열로 만들어 주면 된다.

 

 

 

 

 

 

 

 

 

 

List.js

내가 한 어리석은 실수

export default function List({people}) {
	const {id, name, age, image} = people;
	return (
		<>
			
		</>
	);
}

 

 

상위 App 컴포넌트에서  props로 전달받은 people은 객체를 담고 있는 배열이다!

그래서 destructuring을 people에다가 저런 식으로 하면 안됨!!!!!!!!!!!!!!!

저렇게 코드 치다가 '엌 나 왜 이러고 있냐;;;'하고 급히 지웠음 ㅋㅋ

근데 그래도 이런 무의식 중에 한 실수가 진짜 내 빈구석을 보여주기 때문에.. 부끄럽지만 기록에 남기기로...

 

 

 

 

진짜 제대로 쓴 코드

export default function List({ people }) {
	return (
		<>
			{people.map((person) => {
				const { id, name, age, image } = person;
				return (
					<article key={id} className="person">
						<img src={image} alt={name} />
						<div>
							<h4>{name}</h4>
							<p>{age} years</p>
						</div>
					</article>
				);
			})}
		</>
	);
}

 

people 배열을 map을 이용해서 한바퀴 돌린다~

한 객체 한 객체(person)마다 destructuring을 해서 원하는 JSX를 만든 후 리턴

 

 

 

 

 

 

 

 

 

'React > Mini Projects' 카테고리의 다른 글

Tours (useEffect를 사용해서 데이터 fetch 해보기)  (0) 2021.06.01