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

React Table 05 : Header Groups

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

개별적으로 되어 있는 Header를 그룹핑해주자.

 

방법은 초간단!
Column을 정의해 줄 때 accessor 대신에 columns : [] 에 하위 열을 넣어주면 된다.

export const GROUPED_COLUMNS = [
  {
    Header: "Id",
    Footer: "Id",
    accessor: "id",
  },
  {
    Header: "Name",
    Footer: "Name",
    columns: [
      {
        Header: "First Name",
        Footer: "First Name",
        accessor: "first_name",
      },
      {
        Header: "Last Name",
        Footer: "Last Name",
        accessor: "last_name",
      },
    ],
  },
  {
    Header: "Info",
    Footer: "Info",
    columns: [
      {
        Header: "Date of Birth",
        Footer: "Date of Birth",
        accessor: "date_of_birth",
      },
      {
        Header: "Age",
        accessor: "age",
        Footer: (info) => {
          const avg =
            useMemo(
              () => info.rows.reduce((sum, row) => row.values.age + sum, 0),
              [info.rows]
            ) / info.rows.length;
          return <>Avg : {avg.toFixed(1)} </>;
        },
      },
      {
        Header: "Country",
        accessor: "country",
        Footer: "max Country is ?"
      {
        Header: "Phone",
        Footer: "Phone",
        accessor: "phone",
      },
    ],
  },
];

 

위 코드 작성 후에 useTable에 들어갈 column을 변경해준다.

 

별 거 안했는데 자동으로(?) 반영 되는 이유는 기존에 적용했던 tableInstance 덕분!
아래 코드를 보면 headerGroups 에서 headerGroup을 뽑고, 거기서 또 header 배열에서 각 column을 뽑아내는 걸 알 수 있다.
이렇게 반영된 headerGroups 덕분에 자동으로 반영되는 것 처럼 느껴지는 것임.

      <thead>
        {headerGroups.map((headerGroup) => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map((column) => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>

 

 

 

참고링크

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

 

728x90
반응형

댓글