Search code examples
reactjsreact-bootstrap-table

How to extract table as an indipendente component


I used react-bootstrap-table lib to show tables, and I used a lot (about 10 times ) tables in my project, they all have common options like exportCSV search clearSearch ecc. It makes sense to create a common components (tags) to centralize the BootstrapTable and TableHeaderColumn tag.

I want the following code

    <BootstrapTable data={slotListVM}  exportCSV search options={options}>
                <TableHeaderColumn dataField="id" width="150" dataSort>ID</TableHeaderColumn
    </BootstrapTable>

become

    <Table data={slotListVM}>
                <TableColumn dataField="id">ID</TableColumn>
    </Table>

Is it possible? (I tried, but got Uncaught (in promise) TypeError: Cannot read property 'reduce' of undefined at BootstrapTable.initTable error)

PS: I thought about to centralize the table as a component by pass all the column data, like

    <Table data={slotListVM} colume1={'id'} colume2={'name'}>
    </Table>

but I think

    <Table data={slotListVM}>
                <TableColumn dataField="id">ID</TableColumn>
    </Table>

is a better solution.

Could someone give me some suggestions? Thanks a lot!


Solution

  • What about wrapping react-bootstrap-table lib components - BootstrapTable and TableHeaderColumn into your own stateless functional components, e.g.:

    const Table = ({data, options, children} => (
      <BootstrapTable data={data} options={options} exportCSV search>
        {children}
      </BootstrapTable>
    )
    

    same for TableColumn:

    const TableColumn = ({dataField, children} => (
      <TableHeaderColumn dataField={dataField} width="150" dataSort>
        {children}
      </TableHeaderColumn>
    )
    

    You can read more about it here:

    https://javascriptplayground.com/functional-stateless-components-react/ https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc