본문 바로가기
카테고리 없음

React Table 03 : Quick Start - Basic Table using JSON data

by 이승보 2021. 8. 18.
728x90

이전 글에서는 공식 문서의 코드를 이용해서 시작하는 것을 해봤다면 이번에는 Mockaroo를 이용해서 만든 JSON 파일을 활용해서 테이블을 만들어보려한다.

베이직 테이블(Basic Table) 만들기 순서

  1. Get the data you want to display
  2. Define the columns for your table
  3. Use the data and columns defined to create a table instance using react-table
  4. Define a basic table structure using plain HTML
  5. use the table instance created in step 3 to bring life to the HTML defined in step 4
  6. Include the desired CSS

 

1.데이터 가져오기

JSON파일로 준비 완료!

 

2. 열 정의해주기

columns.js 파일을 별도로 만들어서 열에 대한 정보를 정의해준다.
Header에 대한 정보가 담긴 객체를 배열로 만들어주는데, 이 때 각각의 header에는 accessor라는 key 값이 필요하다
간단하게 얘기하면 아래와 같다.
Header : 표의 머리글에 해당. 표시되는 글자
accessor : 데이터의 객체에서 정의된 각각의 key값
내가 가진 데이터셋에는 email, age에 대한 정보가 있지만, 열을 정의할 때는 모든 key값에 대해 만들어주지 않아도 된다. 필요한 것만! 쏙쏙!

export const COLUMNS = [
  {
    Header: "Id",
    accessor: "id",
  },
  {
    Header: "First Name",
    accessor: "first_name",
  },
  {
    Header: "Last Name",
    accessor: "last_name",
  },
  {
    Header: "Date of Birth",
    accessor: "date_of_birth",
  },
  {
    Header: "Country",
    accessor: "country",
  },
  {
    Header: "Phone",
    accessor: "phone",
  },
];

columns.js 

 

3. React Table 객체 생성하기

BasicTable.js 파일을 테이블 Component를 만들어서 작성해준다.
useTable({열, 데이터}) 로 객체를 만들어주는데, 이 때 useMemo를 사용해서 렌더 할 때마다 재생성하는 것을 방지해준다.
useMemo를 사용하지 않으면 새로운 데이터가 들어올 때 마다 데이터에 들어있는 모든 것을 다시 계산하고 렌더해주게된다.
useTable은 객체를 생성해서 반환해주므로 그걸 넣을 변수를 선언해준다.

import React, {useMemo} from "react"
import {useTable} from "react-table"
import MOCK_DATA from "./MOCK_DATA.json"
import {COLUMNS} from "./columns"

export const BasicTable = () =>{

  const columns = useMemo(() => COLUMNS, [])
  const data = useMemo(() => MOCK_DATA, [])

  //ES6 에서는 꼭 이렇게 key값이랑 매칭 안해줘도 변수명이 같으면 알아서 잘 들어감!
  // const tableInstance = useTable({ columns : columns, data : data })
  const tableInstance = useTable({columns, data})

  return (

  )
}

 

4. HTML 을 이용해서 basic table 만들어주기

return (
    <table>
      <thead>
        <tr>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr></tr>
      </tbody>
    </table>
  );

 

5. tableInstance를 4번에서 만든 basic Table 에 적용해주기

tableInstance를 이용해주기 위해서 필요한 properties를 정의해준다.

const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance;
  • getTableProps : this is a function which needs to be destructured  on the table tag
    <table {...getTableProps()}>​
  • getTableBodyProps : this is a function which need to destructure on tbody tag
    <tbody {...getTableBodyProps()}>​
  • headerGroups : this contains the column heading information which belongs inside the thead tag. this is an array which requires us to use the map method to render the jsx for each header group similar to how you would render a list of elements in any other components
    복잡해보이지만..복잡하게 생각하지말고 하나씩 보자.
    우선 thead 그룹안에 {} 를 이용해서 headerGroups의 headGroup을 꺼내온다. 
    여기 안에 <tr><th> 태그가 들어가며, 다시 <tr> 태그에서는 headerGroup.getHeaderGroupProps 를 연결해주고
    {}을 이용해서 headerGroup.headers 의 각 column 에서 실제 header의 이름을 가져와준다.

    <thead>
    	{headerGroups.map((headerGroup) => (
        	<tr {...headerGroup.getHeaderGroupProps()}>
            	{headerGroup.headers.map((column) => (
                <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
            </tr>
    	))}
    </thead>​
  • rows, preparRow : destructured rows go inside the tbody tag and the code is similar to rendering a list of elements
    <tbody {...getTableBodyProps()}>
            {rows.map((row) => {
              prepareRow(row);
              return (
                <tr {...row.getRowProps()}>
                  {row.cells.map((cell) => {
                    return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
                  })}
                </tr>
              );
            })}
    </tbody>​

완성본

더보기

 

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map((cell) => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );

 

6. 테이블에 CSS 적용하기

CSS는 개취에 따라 하기 나름임! 강의에서는 w3schools.com 에서 그냥 가져왔음 심플하게 : 링크
table.css 파일 만들어서 style 부분 복붙해버림 + 해당 소스에는 'customers' 가 붙어있는데 그냥 다 table로 바꿔버림
그리고는 table.css import해주기

import "./table.css"

 

7. basicTable component를 app에 적용시켜주자!

import React from "react";
import { BasicTable } from "./BasicTable";

return (
	<div>
      <BasicTable />
    </div>
  );

 

완료된 화면

728x90
반응형

댓글