리액트 공식문서의 예제를 보고 만들었습니다.
OnlineStore.js
import React from 'react'
import SearchBar from './SearchBar';
import StoreTable from './StoreTable';
function OnlineStore() {
const datas = [
{category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
{category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
{category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
{category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
{category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
{category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];
return (
<div>
<SearchBar/>
<StoreTable products={datas}/>
</div>
)
}
export default OnlineStore
SearchBar
import React from 'react'
function SearchBar() {
return (
<>
<input placeholder='Search...'/>
<div>
<input type="checkbox" id='stock' />
<label htmlFor='stock'>Only show prodousts in stock</label>
</div>
</>
)
}
export default SearchBar
StoreTable.js
import React from 'react'
function StoreTable(props) {
const {products} = props
const sportingGoods =products.filter(p => p.category==='Sporting Goods')
const electronics =products.filter(p => p.category==='Electronics')
return (
<div>StoreTable</div>
)
}
export default StoreTable
위와 같이 작성을 할 수도 있지만, API로 데이터를 받는 등 확장성을 고려해 작성해보도록 하겠습니다.
//const sportingGoods =products.filter(p => p.category==='Sporting Goods')
//const electronics =products.filter(p => p.category==='Electronics')
products.reduce((acc, cur) => {
if(acc.hasOwnProperty(cur.category)) {
//만약 카테고리를 가지고 있다면, 배열에 추가
return {
...acc,
[cur.category] : [...acc[cur.category], cur]
}
} else {
//새로운 카테고리 key를 생성하고 배열도 추가
return {
...acc,
[cur.category] : [cur]
}
}
}, {})
import React from 'react'
import ProductsTable from './ProductsTable'
function StoreTable(props) {
const {products} = props
const result = products.reduce((acc, cur) => {
if(acc.hasOwnProperty(cur.category)) {
//만약 카테고리를 가지고 있다면, 배열에 추가
return {
...acc,
[cur.category] : [...acc[cur.category], cur]
}
} else {
//새로운 카테고리 key를 생성하고 배열도 추가
return {
...acc,
[cur.category] : [cur]
}
}
}, {})
console.log(result)
//keylist조회
const keys = Object.keys(result)
return (
<table>
<thead>
<tr>
<td>Name</td>
<td>Price</td>
</tr>
</thead>
<tbody>
{keys.map((key, index) => <ProductsTable category={key} items={result[key]} key={index}/>)}
</tbody>
</table>
)
}
export default StoreTable
import React from 'react'
function ProductsTable(props) {
const {category, items} = props
return (
<>
<tr>
<td>{category}</td>
</tr>
{items.map((item, idx) => (
<tr key={idx}>
<td>{item.name}</td>
<td>{item.name}</td>
</tr>
))}
</>
)
}
export default ProductsTable