5

I was looking at this example, and the question I have is for a sticky header. Example: https://material-table.com/#/docs/features/fixed-columns

I was trying to figure out to see if I can get the header that has Name up to BirthPlace to be stick, so that when I create the scroll bar, it will stay there. I tried everything, but it keeps giving me different results. Any help would be great

class BasicFixedColumns extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
    }
  }

  render() {
    return (
      <MaterialTable
        title="Basic Fixed Columns Preview"
        columns={[
          { title: 'Name', field: 'name', width: 150 },
          { title: 'Surname', field: 'surname', width: 150 },
          { title: 'Birth Year', field: 'birthYear', type: 'numeric', width: 150 },
          {
            title: 'Birth Place',
            field: 'birthCity',
            lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
            width: 150
          },
          { title: 'Name', field: 'name', width: 150 },
          { title: 'Surname', field: 'surname', width: 150 },
          { title: 'Birth Year', field: 'birthYear', type: 'numeric', width: 150 },
          {
            title: 'Birth Place',
            field: 'birthCity',
            lookup: { 34: 'İstanbul', 63: 'Şanlıurfa' },
            width: 150
          },
        ]}
        data={[
          { name: 'Mehmet', surname: 'Baran', birthYear: 1987, birthCity: 63 },
          { name: 'Zerya Betül', surname: 'Baran', birthYear: 2017, birthCity: 34 },
        ]}        
        options={{
          fixedColumns: {
            left: 2,
            right: 1
          }
        }}
      />
    )
  }
}
Mark A Avila
  • 157
  • 2
  • 12

1 Answers1

2

You need to set the maxBodyHeight property. Then, when the data exceeds this height, the table will become scrollable with a sticky header.

<MaterialTable
    options={{
        paging: false,
        maxBodyHeight: '300px',
    }}
    columns={columns}
    data={data}
/>

Bonus: For a sticky first column, there is this functionality.

By using this it sets the tableLayout to fixed. I couldn't set it back to auto without the columns becoming a mess. So after creating my columns array I gave the first column some styling:

columns[0].cellStyle = {
    backgroundColor: '#007eff',
    color: '#FFF',
    position: 'sticky',
    left: 0
}
Steve
  • 4,372
  • 26
  • 37
  • 2
    For people visiting this question you can check this https://github.com/mbrn/material-table/issues/780#issuecomment-512876433 – rainversion_3 Apr 06 '21 at 18:43