mardi 24 janvier 2023

How can I Mark Initial value of Checkbox Checked of a single row in React tabl

I am getting a list of Products from an API call and I am rendering it through react-table.

  const getItemsList=()=>{
    getAuthorization()
    .get("product/all_products/")
    .then((res) => {
      setProducts(res.data);
   dispatch(setAPIDetailsItemsTable(res.data));

    })
    .catch((err) => {
      console.log("Error in getting products", err);
    });
  }
  useEffect(() => {
    // Get all products
      getItemsList();
  }, []);

I am using redux for state Management

const data = APIDetailsItemsTable

 const columns = React.useMemo(
    () => [
      {
        Header: "Number",
        accessor: "product_id",
      },
      {
        Header: "Item Name",
        accessor: "name",
      },
      {
        Header: "Item Type",
        accessor: "product_type",
      },
      {
        Header: "Status",
        accessor: "status",
        Cell: StatusPill
      }
 ],
    []
  );

return (
 < AddGuideItemstable
            columns={columns}
            data={data == undefined ? [] : data}
            text="Undefined" />
)
          />

Here is the table component. I am working on Editing part. The checkbox can select only one item from the list.

function AddGuideItemstable({ columns, data, text }) {

 const {
   getTableProps,
   getTableBodyProps,
   headerGroups,
   prepareRow,
   page,
   visibleColumns,
   canPreviousPage,
   canNextPage,
   pageOptions,
   pageCount,
   gotoPage,
   nextPage,
   previousPage,
   setPageSize,
   state,
   preGlobalFilteredRows,
   setGlobalFilter,
   selectedFlatRows,
   state: { selectedRowIds }
 } = useTable(
   {
     columns,
     data,
      initialState: {selectedRowIds},
        stateReducer: (newState, action) => {
       if (action.type === "toggleRowSelected") {
         newState.selectedRowIds = {
           [action.id]: true,
           
         }
       }

       return newState;
   },
   },
   useFilters, // useFilters!
   useGlobalFilter,
   useSortBy,
   usePagination, // new
   useRowSelect,
   (hooks) => {
     hooks.visibleColumns.push((columns) => {
       return [
         ...columns,
         {
           Header: "Choose Items",
           id: "selection",
           Cell: ({ row }) => (
             <div className="flex flex-col ml-6">
               <CheckBox {...row.getToggleRowSelectedProps()}/>
             </div>
           ),
   
 //// dispatching selected item ID if changed 

 useEffect(() => {
   let Id = selectedFlatRows.map(
                 d => d.original.id)
   dispatch(setAddGuideItemID(Id))
   console.log("selected row id", Id)
   }, [selectedRowIds]) 


 // Render the UI for your table
 return (
   <>
             <table
               {...getTableProps()}
               className="min-w-full  bg-transparent divide-y divide-gray-200"
             >
               <thead className=" border-b-8 border-white">
                 {headerGroups.map((headerGroup) => (
                   <tr {...headerGroup.getHeaderGroupProps()}>
                     {headerGroup.headers.map((column) => (
                       // Add the sorting props to control sorting. For this example
                       // we can add them into the header props
                       <th
                         scope="col"
                         className="group px-2 py-3 text-center text-sm font-medium text-gray-400 font-Roboto tracking-wider"
                         {...column.getHeaderProps(
                           column.getSortByToggleProps()
                         )}
                       >
                         <div className="flex items-center justify-between">
                           {column.render("Header")}
                           {/* Add a sort direction indicator */}
                           <span>
                             {column.isSorted ? (
                               column.isSortedDesc ? (
                                 <SortDownIcon className="w-4 h-4 text-gray-100" />
                               ) : (
                                 <SortUpIcon className="w-4 h-4 text-gray-100" />
                               )
                             ) : (
                               <SortIcon className="w-4 h-4 text-gray-100 opacity-0 group-hover:opacity-100" />
                             )}
                           </span>
                         </div>
                       </th>
                     ))}
                   </tr>
                 ))}
               </thead>
               <tbody {...getTableBodyProps()} className="bg-white">
                 {page.map((row, index) => {
                   // new
                   prepareRow(row);
                   return (
                     <tr
                       {...row.getRowProps()}
                       className={
                         index % 2 === 0
                           ? "bg-cyan-100 border-b-8 border-white"
                           : "bg-white border-b-8 border-white"
                       }
                     >
                       {row.cells.map((cell) => {
                         return (
                           <td
                             {...cell.getCellProps()}
                             className="pr-1  pl-2 whitespace-nowrap"
                             role="cell"
                           >
                             {cell.column.Cell.name === "defaultRenderer" ? (
                               <div className="text-sm font-semibold text-black">
                                 {cell.render("Cell")}
                               </div>
                             ) : (
                               cell.render("Cell")
                             )}
                           </td>
                         );
                       })}
                     </tr>
                   );
                 })}
               </tbody>
        
    

The checkbox component is as below

import react, { forwardRef, useEffect, useRef, useState } from "react";

export const CheckBox = forwardRef(({ indeterminate, ...rest }, ref) => {
  const defaultRef = useRef();
  const resolvedRef = ref || defaultRef;

  useEffect(() => {
    resolvedRef.current.indeterminate = indeterminate;
  }, [resolvedRef, indeterminate]);

  return (
    <>
      <div class="flex items-center">
        <input
          type="checkbox"
          ref={resolvedRef}
          {...rest}
          id="A3-yes"
          name="A3-confirmation"
          class="opacity-0 absolute h-8 w-8"
        />
    </>
  );
});

I have an ID stored in a state

let ID =  useSelector((state)=> state.guide.AddGuideResID)

What I want to do is if " ID " in the state is equal to the "ID in the products list" then mark the checkbox checked for that row.

I want to achieve like this. I want to mark only single item thats original ID matches the ID in my redux state. Checkbox checked manually




Aucun commentaire:

Enregistrer un commentaire