Dalal Mansour
Dalal Mansour

Reputation: 317

select component inside checkbox , antd

I'm working on React project with antd and I have a checkbox component, when use mark the checkbox as checked a select options will be displayed.I'll provide my code to be clear.

        <Checkbox
      key={identifier}
      onClick={(e: any) => {
        setSelectedCheckbox(e.target.checked);
        console.log('test=1', e);
      }}
      name={label}
      disabled={viewAssignment}>
      {selectedCheckbox && (
        <Select
          disabled={viewAssignment}
          key={identifier2}
          onSelect={(e: any) => console.log('test=2', e)}
          defaultValue={inputValue}
          notFoundContent={
            <CustomizeRenderEmpty message={t('NOT_FOUND')} />
          }>
          <Select.Option key={'data'} name={'data'} value={'data'}>
            {'data'}
          </Select.Option>
          )
        </Select>
      )}
    </Checkbox>

if selectedCheckbox is true then the select component will be displayed, but the issue when user try to select an option onSelect function will not be called onClick will be called instead with false value e.target.checked equals to false.

is there any way to have Select component inside checkbox without affecting the onClick function if there is any change made in select?

any suggestion will be helpful, thank you.

Upvotes: 3

Views: 1725

Answers (1)

zerocewl
zerocewl

Reputation: 12774

As mr-rogers described correct in his comment, the recommended design is to create a parent component which contains the Checkbox and the Select as separate components. Otherwise the onChange from the Checkbox is always called if a user trys to hit the Select. This is obviously wrong.

A simple example could look like this (here is the Stackblitz too):

import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Checkbox, Select } from 'antd';

const CheckboxDemo = () => {
  const [selectedCheckbox, setSelectedCheckbox] = useState(false);
  return (
    <div>
      <Checkbox
        onChange={e => {
          setSelectedCheckbox(e.target.checked);
          console.log(e.target);
          console.log('test=1', e.target.checked);
        }}
        name="Test"
      >
        Test
      </Checkbox>
      {selectedCheckbox && (
        <Select
          key="2"
          style={{ width: 100 }}
          onChange={e => console.log('test=2', e)}
        >
          <Select.Option key="data1" name="data1" value="data1">
            data 1
          </Select.Option>
          <Select.Option key="data2" name="data2" value="data2">
            data 2
          </Select.Option>
        </Select>
      )}
    </div>
  );
};

ReactDOM.render(<CheckboxDemo />, document.getElementById('container'));

Upvotes: 1

Related Questions