Q. Who is this article for?

  • For those who have used React-Tables and are stuck while adding S.N or an extra column in React-Tables.

Here,

const fields = ['s.n', 'title', 'url', 'state'];

If columns are fetched from backend/api And you want to add the "S.N" column, then

const columnFields = ['s.n'];
columnFields.push(...fields);

This will push elements of fields array into columnFields array such that:

const columnFields = ['s.n', 'title', 'url', 'state'];

Then, inserting s.n cell values:

  const optimizedColumns = columnFields.map((col) => {
        if (col === "s.n") {
            return {
                Header: CapitalizeFirstLetter(col),
                accessor: col,
                /* cell values of s.n column using row.index prop 
                  of react-tables and +1 because index value start 
                 with 0 */
                Cell: (prop) => prop.row.index+1,
            };
        } 
       else {
            return {
                Header: CapitalizeFirstLetter(col),
                accessor: col,
            };
        }
    });

Assuming that you have table data in projects array

//tabledata
const data = React.useMemo(() => projects, []);

//tablecolumn
const columns = React.useMemo(() => optimizedColumns, []);

Useful links: React-Tables example