import React, { useState } from 'react';
function ProductItem({ name, rank, onClick }) {
const isSelected = rank > 0;
const remainingCount = 3 - rank;
const countText = isSelected ? `(${rank}/3)` : ``;
const buttonLabel = isSelected ? '취소' : '상품 비교';
return (
<li>
{name} <span className="count">{countText}</span>
<button type="button" className="compare-btn" onClick={onClick}>
{buttonLabel}
</button>
{!isSelected && remainingCount === 0 && (
<span className="warning">3개 이상 선택할 수 없습니다.</span>
)}
</li>
);
}
export function App(props) {
const [rank, setRank] = useState(Array(5).fill(0));
const handleClick = index => {
const newRank = [...rank];
const selectedRank = newRank.filter(rank => rank > 0);
if (newRank[index] === 0) {
// 선택되지 않은 경우
if (selectedRank.length >= 3) {
alert('3개 이상은 선택할 수 없습니다.');
return;
}
newRank[index] = selectedRank.length + 1;
} else {
// 선택된 경우
newRank[index] = 0;
}
// 순위 재조정
const remainingRank = newRank.filter(rank => rank > 0);
remainingRank.sort((a, b) => a - b);
newRank.forEach((_, i) => {
if (newRank[i] === 0) return;
newRank[i] = remainingRank.indexOf(newRank[i]) + 1;
});
setRank(newRank);
};
return (
<ul>
{rank.map((rank, index) => (
<ProductItem
key={index}
name={`상품 ${index + 1}`}
rank={rank}
onClick={() => handleClick(index)}
/>
))}
</ul>
);
}
import React, { useState } from 'react';
export function App(props) {
const [products, setProducts] = useState([
{ name: '상품1', rank: 0 },
{ name: '상품2', rank: 0 },
{ name: '상품3', rank: 0 },
{ name: '상품4', rank: 0 },
{ name: '상품5', rank: 0 },
]);
const handleClick = (index) => {
const newProducts = [...products];
if (newProducts[index].rank === 0) {
// 순위를 아직 부여하지 않은 경우
const selectedProducts = newProducts.filter((product) => product.rank > 0);
if (selectedProducts.length >= 3) {
alert('3개 이상은 선택할 수 없습니다.');
return;
}
newProducts[index].rank = selectedProducts.length + 1;
} else {
// 이미 순위를 부여한 경우
newProducts[index].rank = 0;
}
// 나머지 상품들의 순위를 조정
newProducts
.filter((product) => product.rank > 0)
.sort((a, b) => a.rank - b.rank)
.forEach((product, i) => {
product.rank = i + 1;
});
setProducts(newProducts);
};
return (
<ul>
{products.map((product, index) => (
<li key={index}>
{product.name} (<span className='count'>{product.rank}</span>/
<span className='totalCount'>3</span>)
<button type='button' className='compare-btn' onClick={() => handleClick(index)}>
상품비교
</button>
</li>
))}
</ul>
);
}
리액트 playground
'Frontend > React' 카테고리의 다른 글
[React Swiper] play, stop 버튼 만들기 (0) | 2023.04.13 |
---|---|
[React Swiper] 리액트에서 스와이퍼 사용하기 (0) | 2023.04.13 |
리액트 연습하기 (0) | 2022.11.16 |
[리액트] JSX란? (0) | 2022.11.16 |
리액트 참고하면 좋은 사이트들 (0) | 2022.11.16 |