Search code examples
javascriptreactjsmdbootstrap

MDBDataTable: how to add a button in a column when data is a json file?


I'm having the MDBTable that looks like this:

//import things
const DatatablePage = () => {
    const data = {
        columns: [
            {
                label: 'Stock Code',
                field: 'StockCode',
                sort: 'asc',
                width: 150
            },
            {
                label: 'Item Description',
                field: 'ItemDes',
                sort: 'asc',
                width: 270
            },
            {
                label: 'Unit Price',
                field: 'UnitPrice',
                sort: 'asc',
                width: 200,
            },
            {
                label: 'In Stock',
                field: 'QUANTITY',
                sort: 'asc',
                width: 100
            },
            {
                label: 'Add to Cart',
                field: null,
                sort: 'asc',
                width: 150
            }
        ],
        rows: table
    };

    return (
        <MDBDataTable
            striped
            bordered
            small
            hover
            theadColor="blue lighten-1"
            data={data}
            btn
            className="blueTable"
        />
    );
}

export default DatatablePage;

The JSON file looks like this (one sample for example):

[{"StockCode":"72800B","ItemDes":"4 PURPLE FLOCK DINNER CANDLES","UnitPrice":2.55,"QUANTITY":17},..]

I want the column "Add To Cart" to have a MDBButton. How do I do that? I searched high and low and I found that I had to insert that MDBButton to the JSON file, per object. Is there any other way?


Solution

  • You can set define the button directly where you prepare your table rows data:

    const table = [
        {..., 
            addBtn : <button className="btn btn-primary" onClick={() => this.addToCart()}>Add</button>
        }
    ]
    

    And in the columns just define the field property with the same name addBtn:

     {
         label: 'Add to Cart',
         field: addBtn
     }