์ํ ๊ด๋ฆฌ ์ฌ์ดํธ๋ฅผ ๊ตฌํ
React ๋ก ์ํ ๋ชฉ๋ก ํ์ด์ง ๊ตฌํ
Card.jsx
import React, { useState } from 'react'
import { Favorite, FavoriteBorder } from "@mui/icons-material";
// const Card = (props) => {
// const Card = ({title, content}) => {
const Card = ({ card }) => {
const { no, title, content, likes, img } = card
// โญ state ์ ์ธ
const [like, setLike] = useState(false)
const [count, setCount] = useState(likes)
// โญ ์ด๋ฒคํธ ํธ๋ค๋ฌ
const handleLike = () => {
setLike( !like )
setCount( !like ? count+1 : count-1 )
console.log(`like : ${like}`)
}
return (
<div style={{
border: "1px solid #ddd",
borderRadius: "10px",
overflow: "hidden",
boxShadow: "0 5px 10px rgba(0,0,0,0.2)",
margin: "0 20px"
}}>
{/* ์ํ ์ด๋ฏธ์ง */}
<img src={ img } width={300} height={200}
style={{ objectFit: 'contain' }}
alt="์ํ์ด๋ฏธ์ง" />
{/* ์ปจํ
์ธ */}
<div style={{ padding: "10px" }}>
<h3 style={{ fontSize: "20px", fontWeight: "bold" }}>
{/* {props.title} */}
{ title }
</h3>
<p style={{ color: "#666", fontSize: "14px" }}>
{/* {props.content} */}
{ content }
</p>
<button
style={{
border: "none",
backgroundColor: "transparent",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
onClick={ handleLike }
>
{
like ?
<Favorite style={{
color: "#ff4757",
fontSize: "40px"
}} />
:
<FavoriteBorder style={{
color: "#ff4757",
fontSize: "40px"
}} />
}
<span style={{
marginLeft: "5px",
fontSize: "24px"
}}>
{ count }
</span>
</button>
</div>
</div>
)
}
export default Card
JavaScript
๋ณต์ฌ
CardList.jsx
import React, { useEffect, useState } from 'react'
import Card from './Card'
const CardList = () => {
// Card ์ปดํฌ๋ํธ์ ์ ๋ฌํ ๋ฐ์ดํฐ
const cardData = [
{
no : 1,
title: '์๋ฉ๋ฆฌ์นด๋
ธ',
content: '์ฝ๋กฌ๋น์ ์๋๋ก ๋ง๋ ...',
likes: 100,
img: 'https://i.imgur.com/D1ic2Xk.jpg'
},
{
no : 2,
title: '์นดํ๋ผ๋ผ',
content: '๋ผ๋ผ๋ ๋ง์ด์ผ...',
likes: 200,
img: 'https://i.imgur.com/hAzIEVv.jpg'
},
{
no : 3,
title: '์ฟ ํคํ๋ผํ',
content: '์ค๋ ์ค ๋คํ๋ค...',
likes: 300,
img: 'https://i.imgur.com/kDhIhLv.jpg'
},
]
// โ useEffect() ํ
์ฌ์ฉ
// "๋ ๋๋ง ์ ํธ์ถ ๋๋ ํจ์"
// : ํจ์ํ ์ปดํฌ๋ํธ์์ ๋ง์ดํธ, ์
๋ฐ์ดํธ, ์ธ๋ง์ดํธ ์๋ช
์ฃผ๊ธฐ ์์
์
// ์ฒ๋ฆฌํ ์ ์๋๋ก ํด์ฃผ๋ ํ
useEffect(() => {
getProductList();
}, []);
return (
<div>
<h1>์ํ ๋ชฉ๋ก</h1>
<div style={{
display: "grid",
gridTemplateColumns: "repeat(4, auto)",
rowGap: "40px"
}}>
{
cardData.map( (card, index) => {
// return <Card key={card.no} title={card.title} content={card.content} />
// return <Card key={card.no} {...card} />
return <Card key={card.no} card={ card } />
})
}
</div>
</div>
)
}
export default CardList
JavaScript
๋ณต์ฌ