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

React Table 03 : Quick Start

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

React Table 에는 <useTable> 이라는 hook과 table <instace> 객체가 있다. <instace> 객체에는 테이블을 작성하고 해당 state와 상호 작용하는 데 필요한 모든 것이 포함되어 있습니다. 여기에는 다음이 포함되지만 이에 국한되지는 않습니다.

  • Columns
  • Materialized Data
  • Sorting
  • Filtering
  • Grouping
  • Pagination
  • Expanded State
  • Any functionality provided by custom plugin hooks, too!

앞서 얘기했듯이, React Table에서 개발자는 테이블의 UI(마크업 및 스타일)를 렌더링할 책임이 있다.

 

베이직 테이블(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

 

데이터 가져오기(Getting your data)

테이블 구조는 열을 포함하는 행을 중첩으로 가져야 하며, 이 때 직접 만든다면 <useMemo>를 사용해야 한다. 나는 시작하기에서 mockaroo를 이용해서 데이터를 만들어줬었다.

 const data = React.useMemo(
   () => [
     {
       col1: 'Hello',
       col2: 'World',
     },
     {
       col1: 'react-table',
       col2: 'rocks',
     },
     {
       col1: 'whatever',
       col2: 'you want',
     },
   ],
   []
 )

Mockaroo를 통해 만든 JSON파일도 열을 포함하는 각각의 행의 배열로 구성되어 있다.

주의 : 우리의 데이터는 모든 렌더에서 다시 생성하지 않도록 React.useMemo를 사용하는 것이 중요하다. 만약 React.useMemo를 사용하지 않는다면 테이블은 렌더링할 때마다 새 데이터를 수신한다고 생각하고 매번 많은 논리를 다시 계산하려고 시도할 것이며 이는 쿨 하지 않아!!ㅋㅋㅋ(Not cool 귀엽)

 

열 정의 (Define Columns)

데이터(배열)를 생성하고 나면 useTable hook에 전달할 열 정의 배열을 생성한다.

 const columns = React.useMemo(
   () => [
     {
       Header: 'Column 1',
       accessor: 'col1', // accessor is the "key" in the data
     },
     {
       Header: 'Column 2',
       accessor: 'col2',
     },
   ],
   []
 )

 

useTable hook 사용(Using the useTable hook)

데이터와 열을 모두 정의했다면, 이 2개를 <useTable> hook으로 전달하면서 table Instance를 만들어준다.
useTable을 사용하기 위해서는 import는 필수

 import { useTable } from 'react-table'
 
 const tableInstance = useTable({ columns, data })

 

기본 테이블 UI 빌드 (Building a basic table UI)

여기까지 진행했지만 실제 화면에서는 아직 테이블이 보이지 않는다. tableInstance를 적용하기 전에 우선 HTML만을 이용해서 기본 테이블을 작성해준다.

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

 

마크업에 테이블 인스턴스 적용 (Applying the table instance to markup)

이제 드디어 만들어 둔 기본 테이블 구조에 tableInstance를 적용해보자. 

const tableInstance = useTable({ columns, data })
 
 const {
   getTableProps,
   getTableBodyProps,
   headerGroups,
   rows,
   prepareRow,
 } = tableInstance
 
 return (
   // apply the table props
   <table {...getTableProps()}>
     <thead>
       {// Loop over the header rows
       headerGroups.map(headerGroup => (
         // Apply the header row props
         <tr {...headerGroup.getHeaderGroupProps()}>
           {// Loop over the headers in each row
           headerGroup.headers.map(column => (
             // Apply the header cell props
             <th {...column.getHeaderProps()}>
               {// Render the header
               column.render('Header')}
             </th>
           ))}
         </tr>
       ))}
     </thead>
     {/* Apply the table body props */}
     <tbody {...getTableBodyProps()}>
       {// Loop over the table rows
       rows.map(row => {
         // Prepare the row for display
         prepareRow(row)
         return (
           // Apply the row props
           <tr {...row.getRowProps()}>
             {// Loop over the rows cells
             row.cells.map(cell => {
               // Apply the cell props
               return (
                 <td {...cell.getCellProps()}>
                   {// Render the cell contents
                   cell.render('Cell')}
                 </td>
               )
             })}
           </tr>
         )
       })}
     </tbody>
   </table>
 )

 

최종결과 (Final Result)

import { useTable } from 'react-table'
 
 function App() {
   const data = React.useMemo(
     () => [
       {
         col1: 'Hello',
         col2: 'World',
       },
       {
         col1: 'react-table',
         col2: 'rocks',
       },
       {
         col1: 'whatever',
         col2: 'you want',
       },
     ],
     []
   )
 
   const columns = React.useMemo(
     () => [
       {
         Header: 'Column 1',
         accessor: 'col1', // accessor is the "key" in the data
       },
       {
         Header: 'Column 2',
         accessor: 'col2',
       },
     ],
     []
   )
 
   const {
     getTableProps,
     getTableBodyProps,
     headerGroups,
     rows,
     prepareRow,
   } = useTable({ columns, data })
 
   return (
     <table {...getTableProps()} style={{ border: 'solid 1px blue' }}>
       <thead>
         {headerGroups.map(headerGroup => (
           <tr {...headerGroup.getHeaderGroupProps()}>
             {headerGroup.headers.map(column => (
               <th
                 {...column.getHeaderProps()}
                 style={{
                   borderBottom: 'solid 3px red',
                   background: 'aliceblue',
                   color: 'black',
                   fontWeight: 'bold',
                 }}
               >
                 {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()}
                     style={{
                       padding: '10px',
                       border: 'solid 1px gray',
                       background: 'papayawhip',
                     }}
                   >
                     {cell.render('Cell')}
                   </td>
                 )
               })}
             </tr>
           )
         })}
       </tbody>
     </table>
   )
 }

 

 

참고 링크

https://react-table.tanstack.com/docs/quick-start

 

Getting Started: Quick Start

Subscribe to our newsletter The latest TanStack news, articles, and resources, sent to your inbox.

react-table.tanstack.com

https://www.youtube.com/watch?v=hson9BXU9F8&list=PLC3y8-rFHvwgWTSrDiwmUsl4ZvipOw9Cz&index=3&ab_channel=Codevolution 

 

728x90
반응형

댓글