skip to Main Content

I have component with table of items. I would like to select few items and be able to do some operation on selected items when i click button under table.

My main table component:

export default function TableComp() {
    function handleSelectedRows() {...}
return (
    <Table>
        ...
        {items.map(item => (
           <TableRowItem item={item}></TableRowItem>
        ))}
    </Table>
    <Button onClick={handleSelectedRows}/>
)}

My TableRowItem component:

function TableRowItem({item}) {
    const [active, setActive] useState(false);
    function handleCLick() {
        setActive(!active);
    }
    return (
        <TableRow onClick={handleCLick} active={active}>...</TableRow>
    )
}

How I could know from Table component what rows was selected?
I could put selected items to the store, but is there any other proper way to get them?

2

Answers


  1. You can store the selected row keys in a state.

    import { useState } from 'react';
    
    function App() {
      const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    
      console.log('selectedRowKeys: ', selectedRowKeys);
      const items = Array.from({ length: 10 }).map((_, i) => ({
        id: i,
      }));
    
      return (
        <table>
          <tbody>
            {items.map((item) => {
              const findIndex = selectedRowKeys.findIndex((k) => k === item.id);
              return (
                <tr
                  style={{ background: findIndex > -1 ? 'green' : 'transparent' }}
                  key={item.id}
                  onClick={() => {
                    if (findIndex > -1) {
                      setSelectedRowKeys(
                        selectedRowKeys.filter((k) => k !== item.id)
                      );
                    } else {
                      setSelectedRowKeys([...selectedRowKeys, item.id]);
                    }
                  }}
                >
                  <td>{item.id}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      );
    }
    
    export default App;
    

    stackblitz

    Login or Signup to reply.
  2. My React Table Component you can handle selecting table rows by maintaining state to track which rows are selected. Here’s a basic example of how you can achieve this:

    import React, { useState } from 'react';
    
    function MyTable() {
        const [selectedRows, setSelectedRows] = useState([]);
    
        const handleRowClick = (rowId) => {
            // Check if the row is already selected
            const selectedIndex = selectedRows.indexOf(rowId);
            let newSelectedRows = [];
    
            if (selectedIndex === -1) {
                // If not selected, add it to the array
                newSelectedRows = [...selectedRows, rowId];
            } else {
                // If already selected, remove it from the array
                newSelectedRows = selectedRows.filter(id => id !== rowId);
            }
    
            // Update the state with the new selected rows
            setSelectedRows(newSelectedRows);
        };
    
        // Function to handle getting all selected row items
        const getAllSelectedItems = () => {
            // Assuming your table data is stored in some array called 'tableData'
            const selectedItems = selectedRows.map(rowId => {
                // Assuming each row has a unique id and its data is stored in an object
                return tableData.find(row => row.id === rowId);
            });
    
            return selectedItems;
        };
    
        return (
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                    </tr>
                </thead>
                <tbody>
                    {tableData.map(row => (
                        <tr key={row.id} onClick={() => handleRowClick(row.id)}>
                            <td>{row.id}</td>
                            <td>{row.name}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
            <div>
                <button onClick={() => console.log(getAllSelectedItems())}>Get Selected Items</button>
            </div>
        );
    }
    
    export default MyTable;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search