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

React Table 04 : Footer 추가하기 + Footer에 합계, 개수 구하기

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

데이터가 많아지다보면 맨 아래 내려갔을 때 각각의 열이 무엇을 의미하는 지 헷갈릴 때가 있다. 또는 열의 마지막 행에 footer를 넣어서 합계,평균 등을 구할 때도 있다. 이 때 각각의 열에 footer를 만들어 줄 수 있다.

 

Step 1. 열 정의하기

열을 정의할 때 기존에 있던 Header, accersor 외에 Footer를 정의해준다.

export const COLUMNS = [
  {
    Header: "Id",
    Footer : "Id",
    accessor: "id",
  },
  {
    Header: "First Name",
    Footer: "First Name",
    accessor: "first_name",
  },
  ....
  ]

 

Step 2. useTable에서 footerGroups 가져오기

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups, //새롭게 추가함
    rows,
    prepareRow,
  } = useTable({ columns, data });

 

Step 3. Table에 footerGroups 적용하기

headerGroups를 적용한 것과 동일한 방식이다.

<tfoot>
        {footerGroups.map((footerGroup) => (
          <tr {...footerGroup.getFooterGroupProps()}>
            {footerGroup.headers.map((column) => (
              <td {...column.getFooterProps}>{column.render("Footer")}</td>
            ))}
          </tr>
        ))}
</tfoot>

 

Step4. CSS 적용하기

 

결과

 

 

+ 계산식을 추가하는 방법 : 나이의 평균 구하기

{
    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} </>;
    },
  },

 

+ 가장 많은 개수의 나라 구하기

  {
    Header: "Country",
    accessor: "country",
    Footer: (data) => {
      const result = useMemo(() => {
        const countriesCnt = [];

        return data.rows.reduce(
          (acc, row, i) => {
            const curCountry = row.values.country;
            let tempCnt = 0;
            if (
              countriesCnt.find((obj) => {
                if (obj.Country === curCountry) {
                  obj.Cnt++;
                  tempCnt = obj.Cnt;
                  return true;
                } else {
                  return false;
                }
              })
            ) {
            } else {
              countriesCnt.push({
                Id: i,
                Country: curCountry,
                Cnt: 1,
              });
              tempCnt = 1;
            }

            if (acc["Cnt"] < tempCnt) {
              acc["Name"] = curCountry;
              acc["Cnt"] = tempCnt;
            }

            return acc;
          },
          { Name: "", Cnt: 0 }
        );
      }, [data.rows]);

      console.log(result);

      return (
        <>
          <span>max Country : </span>
          <span>
            {result.Name}({result.Cnt})
          </span>
        </>
      );
    },
  },
728x90
반응형

댓글