javascriptreactjstypescriptantdmultipleselection

how to sync the antd multiple select table checkbox state with a select option


I have antd multiple row selectable table and for each row a select option is there. and when I click on a checkbox the row should get selected and the defaultvalue of select should change to "Active". when I untick the checkbox the row should not get selected and the defaultvalue of select should change to "Inactive". also when I select the option as Active, the checkbox of that row should get ticked. and when I give the option as Inactive checkbox should be unticked.

Anyone know how to achive this?

const columns = [
{
      title: "name",
      dataIndex: "name",
      key: "name",
    },
{
      title: "status",
      dataIndex: "status",
      key: "status",
      render: (text: any, record: any) => {
        return (
          <Select  style={{ width: 120 }} >
            <Option value="Active">Active</Option>
            <Option value="Inactive">Inactive</Option>
          </Select>
        );
      },
    },
]

const dataSource = [
 {
      key: "1",
      name: "Mike",
      status: null,
    },
{
      key: "2",
      name: "jane",
      status: null,
    },
]

const rowSelection = { 
     onChange: (selectedRowKeys: any, selectedRows: any) => {
      console.log("selectedRows ",selectedRows)
      console.log("selectedRows ",selectedRowKeys)
      },
    getCheckboxProps: (record: any) => ({
    
      
    }),
  };

return(
<Table
        columns={columns}
        rowSelection={{ type: "checkbox", ...rowSelection }}
        dataSource={dataSource}
      />
)

Solution

  • You should use state value for Select component.

    const [selectedValues, setSelectedValues] = useState(null);
    
    <Select  style={{ width: 120 }} value={selectedValues.find(/*write find function that will based on key of record*/) ? "Active" : "Inactive"} >
                <Option value="Active">Active</Option>
                <Option value="Inactive">Inactive</Option>
              </Select>
    
    
    const rowSelection = { 
         onChange: (selectedRowKeys: any, selectedRows: any) => {
          console.log("selectedRows ",selectedRows)
          console.log("selectedRows ",selectedRowKeys)
    
          setSelectedValues(selectedRows);
          },
        getCheckboxProps: (record: any) => ({
        
          
        }),
      };