简体   繁体   中英

react-table column from sum of other columns

I am really new in react-table v6 (I found v7 overcomplicated), so I cannot get few things:

I want to make a column from the sum of other columns of periodical table, for ex. element Ferrum + element Molybdenum. I want to sum both values from the row and, if it exceeds some certain value to color it in different colors. I get to call a func from a cell, but... I pick some code from here React-table Individual Cell Style

                    {
                        Header: 'Fe + Mo',
                        headerClassName: "header-class",
                        className: "row-class",
                        getProps: (state, rowInfo, column) => {
                            console.log(rowInfo);
                            return {
                                style: {
                                    background: rowInfo && rowInfo.row.WHAT_SHOULD_BE_THERE > 10 ? 'red' : null,
                                },
                            };
                        },
                        width: 80,
                        Cell: props =>  <span> {sumColumnFormatter(props.row, "elementFe", "elementMo" )}</span>
                    },

I am also trying to put some border after certain column like this

                        getProps: (state, rowInfo, column) => {
                            return {
                                style: {
                                    borderRight: '10px black'
                                }
                            }
                        }

But it doesn't work.

So the code for the column is above.

The unclear moments are:

  • why the getProps is used and what are rowInfo, state and column? Why it is sometimes rowInfo undefined?

  • what do I have to type when I use the rowInfo.row to access my column with the sum and, depending on that sum, colorize it? There is undefined: undefined listed among other columns in rowInfo, when rowInfo is not undefined

  • what are the units I set the width with? What does it means 80?

Well I just added a func that summarize requested columns outside the table. Inside the table I did

                    Cell: cell => {
                        const value = sumColumnFormatter(cell.row, param1, param2);
                        return (
                        <span> {value}</span>
                        )
                    }

I prepared an example with version 7.1.0 . Please check it.

import React from 'react'
import styled from 'styled-components'
import {useTable} from 'react-table'
import namor from 'namor';

const range = len => {
    const arr = [];
    for (let i = 0; i < len; i++) {
        arr.push(i)
    }
    return arr
};

const newPerson = () => {
    const statusChance = Math.random();
    const jIncome = Math.floor(Math.random() * 30);
    const bIncome = Math.floor(Math.random() * 100);

    return {
        firstName: namor.generate({words: 1, numbers: 0}),
        lastName: namor.generate({words: 1, numbers: 0}),
        jIncome: jIncome,
        bIncome: bIncome,
        tIncome: jIncome + bIncome,
        progress: Math.floor(Math.random() * 100),
        status:
            statusChance > 0.66
                ? 'relationship'
                : statusChance > 0.33
                ? 'complicated'
                : 'single',
    }
};

function makeData(...lens) {
    const makeDataLevel = (depth = 0) => {
        const len = lens[depth];
        return range(len).map(d => {
            return {
                ...newPerson(),
                subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
            }
        })
    };

    return makeDataLevel()
}

const Styles = styled.div`
  padding: 1rem;

  table {
    border-spacing: 0;
    border: 1px solid black;

    tr {
      :last-child {
        td {
          border-bottom: 0;
        }
      }
    }

    th,
    td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;

      :last-child {
        border-right: 0;
      }
    }
  }
`;

function Table({columns, data}) {
    // Use the state and functions returned from useTable to build your UI
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = useTable({
        columns,
        data,
    });

    // Render the UI for your table
    return (
        <table {...getTableProps()}>
            <thead>
            {headerGroups.map(headerGroup => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                    {headerGroup.headers.map(column => (
                        <th {...column.getHeaderProps()}>{column.render('Header')}</th>
                    ))}
                </tr>
            ))}
            </thead>
            <tbody {...getTableBodyProps()}>
            {rows.map((row, i) => {
                prepareRow(row);
                return (
                    <tr {...row.getRowProps(
                        {
                            style: {backgroundColor: row.values.tIncome > 50? 'skyblue': 'lightgray'}
                        }
                    )}>
                        {row.cells.map(cell => {
                            return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                        })}
                    </tr>
                )
            })}
            </tbody>
        </table>
    )
}

function ReactTableRowColor() {
    const columns = React.useMemo(
        () => [
            {
                Header: 'Name',
                columns: [
                    {
                        Header: 'First Name',
                        accessor: 'firstName',
                    },
                    {
                        Header: 'Last Name',
                        accessor: 'lastName',
                    },
                ],
            },
            {
                Header: 'Info',
                columns: [
                    {
                        Header: 'Job Income',
                        accessor: 'jIncome',
                    },
                    {
                        Header: 'Business Income',
                        accessor: 'bIncome',
                    },
                    {
                        Header: 'Total Income',
                        accessor: 'tIncome',
                    },
                    {
                        Header: 'Status',
                        accessor: 'status',
                    },
                    {
                        Header: 'Profile Progress',
                        accessor: 'progress',
                    },
                ],
            },
        ],
        []
    );

    const data = React.useMemo(() => makeData(20), []);

    return (
        <Styles>
            <Table columns={columns} data={data}/>
        </Styles>
    )
}

export default ReactTableRowColor

If you want to use version 6.8.6 then you can check this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM