Search code examples
reactjsbootstrap-4react-bootstrapreact-bootstrap-table

Table creating more table rather than a new row


I am trying to populate my React Bootstrap table data using a single array of objects. I want to create a new row for each obj and with one table header for each column, but instead it's creating new tables instead.

I tried to move the map function ("this.props.data.map((person, key) =>") inside where is called/rendered and few other places, so it doesn't call the componenet multiple times, but I am having hard time with the syntax.

const columns = [{
    dataField: 'id',
    text: 'ID'
}, {
    dataField: 'firstName',
    text: 'First Name'
}, {
    dataField: 'lastName',
    text: 'Last Name',
    sort: true
}, {
    dataField: 'birthDate',
    text: 'Birth Date'
}, {
    dataField: 'email',
    text: 'Email'
}];

    render(){
        return(
            <div>
                {this.props.data.map((person, key) =>
                    <div key={key} >
                        <BootstrapTable
                            hover
                            condensed={true}
                            bootstrap4={true}
                            keyField='id'
                            data={person}
                            columns={columns}
                            />
                    </div>
                )}
            </div>
        );
    }

Solution

  • You don't need to map through the array. All you need to do is put this.props.data into the data field.

    data={this.props.data}
    

    Then, as long as the keys i.e firstName, lastName etc... are in the objects, it shouldl print the table for you.

    This is assuming your array looks like:

    [{firstName: 'Bob', lastName: 'Sagget',...}, {firstName: 'George', lastName: 'Bobbish',... }]
    

    Full return statement:

    return(
            <div>
                 <BootstrapTable
                  hover
                  condensed={true}
                  bootstrap4={true}
                  keyField='id'
                  data={this.props.data}
                  columns={columns}
                  />
            </div>
        );