javascriptreactjsreact-tablereact-table-v7

How to convert decimal number from the accessor to react-table?


I am using react table. On my data, I have fields that have decimal numbers. I need to apply the function of round off on the data of the decimal numbers. I hope you could help me. Thank you

   const columns = useMemo(
        () => [
          {
            Header: 'Rank',
            id: 'index',
            accessor: (function (_row, i) { return i + 1; })
          
        },
        
          {
            Header: "Username",
            accessor: "username"
          },
          {
            Header: "Score",
            accessor: 'score',
            Cell: (row) => {
              return <div>{Math.round(row)}</div>;
            },
          },
          
        ],
        []
      );

Solution

  • The function passed to Cell takes the first argument as an object with more data. To round the number by passing a funciton to Cell, use:

    Cell: (obj) => Math.round(obj.value)
    

    Or pass a function to the accessor:

    accessor: (obj) => Math.round(obj.score)