Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Table Component Checkbox Selection Issue #1528

Open
darundevs opened this issue Sep 1, 2024 · 1 comment
Open

Table Component Checkbox Selection Issue #1528

darundevs opened this issue Sep 1, 2024 · 1 comment

Comments

@darundevs
Copy link

darundevs commented Sep 1, 2024

When I select the checkbox, I don't get the active checkbox state, resulting in multiple duplicated selected items.

Source :

"use client";

import React, { useState } from 'react';
import { Table } from '@bigcommerce/big-design';

interface Item {
  sku: string;
  name: string;
  stock: number;
}

export default function Example() {
  const [selectedItems, setSelectedItems] = useState<Item[]>([]);

  const columns = [
    {
      header: 'SKU',
      hash: 'sku',
      render: ({ sku }: Item) => sku,
    },
    {
      header: 'Name',
      hash: 'name',
      render: ({ name }: Item) => name,
    },
    {
      header: 'Stock',
      hash: 'stock',
      render: ({ stock }: Item) => stock,
    },
  ];

  const data: Item[] = [
    { sku: 'SM13', name: '[Sample] Smith Journal 13', stock: 25 },
    { sku: 'DPB', name: '[Sample] Dustpan & Brush', stock: 34 },
    { sku: 'OFSUC', name: '[Sample] Utility Caddy', stock: 45 },
    { sku: 'CLC', name: '[Sample] Canvas Laundry Cart', stock: 2 },
    { sku: 'CGLD', name: '[Sample] Laundry Detergent', stock: 29 },
  ];

  const handleSelectionChange = (selectedItems: Item[]) => {
    setSelectedItems(selectedItems);
    console.log('Selected items:', selectedItems);
  };

  return (
    <Table
      columns={columns}
      items={data}
      itemName="Products"
      keyField="sku"
      selectable={{
        onSelectionChange: handleSelectionChange,
        selectedItems: selectedItems,
      }}
    />
  );
}

image

@chanceaclark
Copy link
Contributor

Hey @darundevs,

That is due to everytime you select an option, selectedItems changes and rerenders the component creating new references for data. Since selectedItems is an array of JS references they are not going to the same references as data anymore. If you move data outside of the export default function Example() {}, you'll see it works normally.

Best practice in these cases is to pass in data as a prop to your component that way it doesn't create new references.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants