React에서 객체 배열을 HTML 테이블로 출력하기
다시 우리의 제품 배열이 주어졌다고 가정해 봅시다:
const prods = [
{id: 1, name: 'product1', cost: 100},
{id: 2, name: 'product2', cost: 200},
{id: 3, name: 'product3', cost: 300},
];
배열 요소를 HTML 테이블 형태로 출력해 봅시다:
function App() {
const rows = prods.map(function(item) {
return <tr key={item.id}>
<td>{item.name}</td>
<td>{item.cost}</td>
</tr>;
});
return <table>
<tbody>
{rows}
</tbody>
</table>;
}
테이블에 열 제목을 추가해 봅시다:
function App() {
const rows = prods.map(function(item) {
return <tr key={item.id}>
<td>{item.name}</td>
<td>{item.cost}</td>
</tr>;
});
return <table>
<thead>
<tr>
<td>제품명</td>
<td>가격</td>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>;
}
App 컴포넌트에 다음 배열이 주어졌습니다:
const users = [
{id: 1, name: 'user1', surn: 'surn1', age: 30},
{id: 2, name: 'user2', surn: 'surn2', age: 31},
{id: 3, name: 'user3', surn: 'surn3', age: 32},
];
이 배열의 요소를 table 태그를 사용해 테이블로 출력하세요.
객체의 각 필드는 자체 td 태그 안에 들어가야 합니다.
테이블의 열 제목도 만들어 보세요.