DataTable with Dynamic Columns and Templating
Posted: 20 May 2019, 06:24
I'm setting up a DataTable using Dynamic Columns, and I want to have a Dynamic Template for some of the data - for example, showing an icon based on the text content returned by my API.
I'm following the examples in the documentation, but I don't see a way to do this.
I'm using this example to build my Dynamic Columns (straight from the documentation https://www.primefaces.org/primereact/#/datatable):
And I want to use this code to use the templates (also straight from the documentation):
So how do I put bodyTemplate={this.brandTemplate} into my dynamic columns code?
I'm following the examples in the documentation, but I don't see a way to do this.
I'm using this example to build my Dynamic Columns (straight from the documentation https://www.primefaces.org/primereact/#/datatable):
Code: Select all
render() {
let cols = [
{field: 'vin', header: 'Vin'},
{field: 'year', header: 'Year'},
{field: 'brand', header: 'Brand'},
{field: 'color', header: 'Color'}
];
let dynamicColumns = cols.map((col,i) => {
return <Column key={col.field} field={col.field} header={col.header} />;
});
return (
<DataTable value={this.state.cars}>
{dynamicColumns}
</DataTable>
);
}
Code: Select all
brandTemplate(rowData, column) {
var src = "showcase/resources/demo/images/car/" + rowData.brand + ".png";
return <img src={src} alt={rowData.brand}/>;
}
render() {
var carCount = this.state.cars ? this.state.cars.length: 0;
var header = <div className="p-clearfix" style={{'lineHeight':'1.87em'}}>List of Cars <Button icon="pi pi-refresh" style={{'float':'right'}}/></div>;
var footer = "There are " + carCount + ' cars';
return (
<DataTable value={this.state.cars} header={header} footer={footer}>
<Column field="vin" header="Vin" />
<Column field="year" header="Year" />
<Column field="brand" header="Brand" bodyTemplate={this.brandTemplate} style={{textAlign:'center'}}/>
<Column field="color" header="Color" bodyTemplate={this.colorTemplate} />
<Column body={this.actionTemplate} style={{textAlign:'center', width: '6em'}}/>
</DataTable>
);
}