Categories
JavaScript React

Make Expandable Rows with React-Bootstrap-Table2

Spread the love

With react-bootstrap-table-2, we can create expandable rows with the built in BoostrapTable component.

To use it, we install it by running:

npm install react-bootstrap-table-next --save

Then we write:

import React from "react";
import BootstrapTable from "react-bootstrap-table-next";
import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css";

const expandRow = {
  renderer: row => <div>age: {row.age}</div>
};

const columns = [
  {
    dataField: "id",
    text: "ID"
  },
  {
    dataField: "firstName",
    text: "first name"
  },
  {
    dataField: "lastName",
    text: "last name"
  }
];

const persons = [
  { id: 1, firstName: "james", lastName: "smith", age: 20 },
  { id: 2, firstName: "alex", lastName: "green", age: 20 },
  { id: 3, firstName: "may", lastName: "jones", age: 18 }
];

export default function App() {
  return (
    <div className="App">
      <BootstrapTable
        keyField="id"
        data={persons}
        columns={columns}
        expandRow={expandRow}
      />
    </div>
  );
}

We import the BootstrapTable component and the css that comes with react-bootstrap-table-2.

Then we create an object called expandRow that displays something in the expanded row.

row has the data for an entry, so we just access the property in the component we return.

columns has the columns data. dataField is for the key for the field of the entry.

text is the column heading text that’s corresponds to the key name.

persons has the data we want to display.

In App, we use the BootstrapTable component by passing in the objects that we created before.

expandRow has the object that’s used to display them items when the row is expanded.

data has the data. keyField has the property name for the unique key.

columns has the data for the columns.

Once we wrote the code above, we see the age field when we click on a row.

With react-bootstrap-table-2, we can make tables with expandable rows without much hassle.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.