Search code examples
primereact

headerStyle in Dynamic Columns primereact datatable


I'm using dynamic columns in PrimeReact Datatable component:

const columns = [
  {
    field: 'code',
    header: 'Code',
    body: bodyTemplate,
    headerStyle: {{minWidth: '15rem'}},
    sortable: 'sortable',
  },
  ...
]

I defined bodyTemplate as:

const bodyTemplate = (rowData) => {
  return (
    <>
      <span className='p-column-title'>Code</span>
      {rowData.code}
    </>
  )
}

But I don't know how to define headerStyle. Is it possible and how can I do that in dynamic columns?


Solution

  • I did it as follow:

    change

    headerStyle: {{minWidth: '15rem'}}

    to

    headerStyle: {minWidth: '15rem'}

    in columns array as:

    const columns = [
      {
        field: 'code',
        header: 'Code',
        body: bodyTemplate,
        headerStyle: {minWidth: '15rem'},
        sortable: 'sortable',
      },
      ...
    ]
    

    and then in Datatable map columns define headerStyle={col.headerStyle} as:

    {columns.map((col) => (
      <Column
        field={col.field}
        header={col.header}
        body={col.body}
        sortable={col.sortable}
        headerStyle={col.headerStyle}
      />
    ))}