Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- next.js
- react-hook-form
- 다중map
- 구조분해할당
- React
- wecode
- ToyProject
- Tanstack Query
- teamproject
- useForm
- 팀프로젝트
- JS
- javascript
- wescanner
- html
- 일본 우편번호 api
- miniproject
- 이중map
- 구조화된 데이터
- TIL
- toy project
- 리액트네이티브
- project
- useEffect
- 다음은 메인페이지
- 문제
- 처음부터 배포까지
- css
- Threppa
- mini
Archives
- Today
- Total
블로그 이름을 입력해주세요
[React] monster 컴포넌트 연습! 본문
부트캠프 수강 중 컴포넌트를 연습할 수 있는 monster 사이트를 정리해본다
1. API 주소: https://jsonplaceholder.typicode.com/users
위 주소를 호출하여 데이터 로딩을 처리해주세요!
- useEffect()
- fetch
- setState (monsters 에 저장)
먼저 fetch함수를 사용하여 API를 호출하여 데이터 로딩이 잘 되는지 확인한다
fetch('https://jsonplaceholder.typicode.com/users', { method: "GET" })
.then((res) => res.json())
.then((data) => {
console.log(data)
})
API주소를 통해 데이터 로딩이 잘 불러와졌다
콘솔 로그 무조건 자주 찍어 확인해보자
useEffect를 통해서 초기 렌더링이 진행될 때 데이터 로딩만 해주면 될 거 같다
const [monsters, setMonsters] = useState([]);
const [userInput, setUserInput] = useState("");
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users', { method: "GET" })
.then((res) => res.json())
.then((monstersData) => {
setMonsters(monstersData)
})
}, []);
그리고 미리 만들어져 있는 setMonsters state안에 fetch로 불러온 데이터를 넣어주면 사용 준비 끝
2. API 호출의 결괏값 props로 자식에게 전달
자식 컴포넌트에 부모 컴포넌트가 가지고 있는 데이터를 주려면 props를 사용해야 한다
props로 넘겨주고 콘솔 로그가 잘 찍히는지 확인
return (
<div className="monsters">
<h1>컴포넌트 재사용 연습!</h1>
{/* <SearchBox handleChange=정의한메소드 /> */}
<CardList monsters={monsters} />
</div>
);
Cardlist.js
function CardList(props) {
console.log("props", props)
return <div className="cardList"></div>;
}
3. Array.map() 사용
function CardList({ monsters }) {
return (
<div className="cardList">
{
monsters.map((monster) => {
return (
<Card key={monster.id} id={monster.id} email={monster.email} name={monster.name} />
)
})
}
</div>
)
}
그리고 card.js에 사용할 props 데이터 넘겨주기
card.js
function Card({ name, id, email }) {
return (
<div className="cardContainer">
<img src={`https://robohash.org/${id}?set=set2&size=180x180`} alt="" />
<h2>{name}</h2>
<p>{email}</p>
</div>
)
}
최종 결과 화면
'javaScript' 카테고리의 다른 글
[React] class동적으로 구현하기 (0) | 2022.06.28 |
---|---|
[React] Component화 활용하기 (0) | 2022.06.26 |
[React] react 구조분해 할당? (0) | 2022.06.18 |
[React] map()을 통한 반복적인 태그 줄이기 (0) | 2022.06.17 |
[React] useEffect ?? (0) | 2022.06.15 |