Untitled
unknown
javascript
10 months ago
5.8 kB
34
Indexable
import { useState, useEffect } from 'react';
function ShoppingMall() {
const [products, setProducts] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [searchKeyword, setSearchKeyword] = useState('');
const [category, setCategory] = useState('전체보기');
const [sortOrder, setSortOrder] = useState('name'); // name, price, stock
useEffect(() => {
loadProducts();
}, []);
const loadProducts = () => {
setIsLoading(true);
setError(null);
setTimeout(() => {
setProducts([
{
id: 'prod_001',
name: '무선 키보드',
category: '전자제품',
price: 45000,
originalPrice: 50000,
stock: 10,
isNew: true,
isOnSale: true,
},
{
id: 'prod_002',
name: '게이밍 마우스',
category: '전자제품',
price: 30000,
originalPrice: 30000,
stock: 0,
isNew: false,
isOnSale: false,
},
{
id: 'prod_003',
name: '노트북 스탠드',
category: '사무용품',
price: 20000,
originalPrice: 25000,
stock: 5,
isNew: true,
isOnSale: true,
},
{
id: 'prod_004',
name: 'USB-C 허브',
category: '전자제품',
price: 35000,
originalPrice: 40000,
stock: 15,
isNew: false,
isOnSale: true,
},
{
id: 'prod_005',
name: '책상 매트',
category: '사무용품',
price: 15000,
originalPrice: 15000,
stock: 20,
isNew: false,
isOnSale: false,
},
]);
setIsLoading(false);
}, 200);
};
const getFilteredProducts = () => {
let filtered = [...products];
console.log('Current category:', category);
console.log(filtered);
if (category !== '전체보기') {
console.log('Filtering by category:', category);
filtered = filtered.filter((product) => product.category === category);
}
if (searchKeyword.trim() !== '') {
console.log('Filtering by search keyword:', searchKeyword);
filtered = filtered.filter((product) =>
product.name.toLowerCase().includes(searchKeyword.toLowerCase())
);
}
console.log('Filtered products before sorting:', filtered);
filtered.sort((a, b) => {
if (sortOrder === 'name') {
return a.name.localeCompare(b.name);
} else if (sortOrder === 'price') {
return a.price - b.price;
} else if (sortOrder === 'stock') {
return b.stock - a.stock;
}
return 0;
});
console.log('Filtered products after sorting:', filtered);
return filtered;
};
const filteredProducts = getFilteredProducts();
const categories = ['전체보기', '전자제품', '사무용품'];
if (isLoading) {
return (
<div>
<h1>React 쇼핑몰</h1>
<p>상품을 불러오는 중입니다...</p>
</div>
);
}
if (error) {
return (
<div>
<h1>React 쇼핑몰</h1>
<p>상품을 불러오는 중에 오류가 발생했습니다: {error}</p>
<button onClick={loadProducts}>다시 시도</button>
</div>
);
}
return (
<div>
<h1>React 쇼핑몰</h1>
<div>
<input
type="text"
placeholder="검색어 입력"
value={searchKeyword}
onChange={(e) => setSearchKeyword(e.target.value)}
/>
</div>
<div>
<select value={category} onChange={(e) => setCategory(e.target.value)}>
{categories.map((cat) => (
<option key={cat} value={cat}>
{cat}
</option>
))}
</select>
<select value={sortOrder} onChange={(e) => setSortOrder(e.target.value)}>
<option value="name">이름순</option>
<option value="price">낮은 가격순</option>
<option value="stock">재고 많은 순</option>
</select>
</div>
{filteredProducts.length > 0 && (
<div>
<p>
{searchKeyword && `"${searchKeyword}"의 검색 결과: `}
{filteredProducts.length}개 상품
</p>
</div>
)}
{filteredProducts.length === 0 ? (
<p>조건에 맞는 상품이 없습니다.</p>
) : (
<ul>
{filteredProducts.map((product) => (
<li key={product.id} style={{ marginBottom: '20px' }}>
<h2>
{product.name} {product.isNew && <span style={{ color: 'green' }}>신상품</span>}{' '}
{product.isOnSale && <span style={{ color: 'red' }}>세일 중</span>}
</h2>
<p>카테고리: {product.category}</p>
<p>
가격: {product.price.toLocaleString()}원{' '}
{product.isOnSale && product.originalPrice > product.price && (
<span style={{ textDecoration: 'line-through', color: 'gray' }}>
{product.originalPrice.toLocaleString()}원
</span>
)}
</p>
<p>재고: {product.stock > 0 ? `${product.stock}개` : '품절'}</p>
</li>
))}
</ul>
)}
</div>
);
}
export default function App() {
return (
<>
<ShoppingMall />
</>
);
}
Editor is loading...
Leave a Comment