reactjsmdbtable

Add sorting to MDBTable


I am trying to add sorting to my table. I am trying to avoid reformatting the json with columns: [{}].
Instead, I would like to add the sorting option directly in the MDBTable data.

Is this possible? Or can I specify the columns to the MDBTable?

The below code works fine, but the columns are not sortable.

render() {
  return (
    <div>
      <h1 className="text-center">Coronastatistik för sverige</h1>
      <MDBTable>
        <MDBTableHead>
          <tr>
            <th>Regtion</th>
            <th>Fall</th>
            <th>Fall per 100 000 invånare</th>
            <th>Procent av fall i Sverige</th>
          </tr>
        </MDBTableHead>
        <MDBTableBody>
          {this.state.regions.map(region => (
            <tr>
              <td>{region.Region}</td>
              <td>{region.Fall.toLocaleString()}</td>
              <td>{region.Incidens}</td>
              <td>{region.Procent} %</td>
            </tr>
          ))}
        </MDBTableBody>
      </MDBTable>
    </div>
    );
}

Solution

  • To be able to sort a MDBTable first you have to do it as a MDBDataTable. Then in my case I had to create the json object with the data it needs. For me the messy part was to understand how to build a suitable json object. But after that the table was no problem.

    This requires an object in this format

    data: {
    columns: [{
            label: 'Name',
            field: 'name',
            sort: 'asc',
            width: 150 }],
    rows: [
          {
            name: 'Tiger Nixon',
            position: 'System Architect',
            office: 'Edinburgh',
            age: '61',
            date: '2011/04/25',
            salary: '$320'
          }}
    

    Then you return the MDBDataTable

    return (
        <MDBDataTable
          striped
          bordered
          small
          data={data}
        />
      );