Help with using InputSwitch Inside of DataTable

UI Components for React
Post Reply
thebr
Posts: 3
Joined: 24 May 2022, 06:13

24 May 2022, 14:08

Hi there, I am trying to use InputSwitch to toggle every row inside of my DataTable.
Right now, I am using this approach: In the array of objects containing the values of DataTable, I define a field that has the InputSwitch element as follows:

Code: Select all

        const data= [
            {
                id: "1000",
                code: "f230fh0g3",
                name: "Bamboo Watch",
                description: "Product Description",
                image: "bamboo-watch.jpg",
                price: 65,
                category: "Accessories",
                quantity: 24,
                inventoryStatus: "INSTOCK",
                rating: 5,
                action: (
                    <InputSwitch
                        onChange={(e) => {
                        console.log(e.target);
                        }}
                    />
                ),
            },...]
and for the DataTable:

Code: Select all

          <DataTable value={notificationsData} responsiveLayout="scroll" >
                    <Column field="code" header="Code"></Column>
                    <Column field="name" header="Name"></Column>
                    <Column field="category" header="Category"></Column>
                    <Column field="quantity" header="Quantity"></Column>
                    <Column field="action" header="Active"></Column>
                </DataTable>
However, in this approach, when I click on the InputSwitch, I have no way of knowing which row it corresponds to. Also, it is a bit of a hassle to add <InputSwitch> to every object as these objects will be fetched from the database.
Does anyone know a better way to tackle this problem?

Thanks a lot in advance.

Melloware
Posts: 3716
Joined: 22 Apr 2013, 15:48

24 May 2022, 15:05

Don't pass the InputSwitch in your JSON just use a bodyTemplate on that column and add the input switch and the bodyTemplate options passes you the "row" data object so you can determine which row it is.

See: https://primefaces.org/primereact/datatable/templating/
PrimeFaces Developer | PrimeFaces Extensions Developer
GitHub Profile: https://github.com/melloware
PrimeFaces Elite 13.0.0 / PF Extensions 13.0.0
PrimeReact 9.6.1

thebr
Posts: 3
Joined: 24 May 2022, 06:13

25 May 2022, 08:25

That fixed my issue! Thanks a lot. I don't know how I failed to read about it.

Thanks again.

Melloware
Posts: 3716
Joined: 22 Apr 2013, 15:48

25 May 2022, 13:34

Awesome! No problem.
PrimeFaces Developer | PrimeFaces Extensions Developer
GitHub Profile: https://github.com/melloware
PrimeFaces Elite 13.0.0 / PF Extensions 13.0.0
PrimeReact 9.6.1

Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: SLS_bjMt and 10 guests