Search code examples
javascriptreactjsant-design-pro

How to render default value in ant design checkbox using boolean?


I am trying to render a checkbox default value using ant-design.

Here is the data I want to render

plainOptions: [
    {
        name: "apple",
        is_enabled: "true",
    },
    {
        name: "orange",
        is_enabled: "true"
    },
    {
        name: "banana",
        is_enabled: "true"      
    },
    {
        name: "grape",
        is_enabled: "false",
    },
]

And here is the component :

                    <FormItemRow>
                        <Col span={24} style={colStyle}>
                            <FormItem label={'fruits'} colon={ false } style={{ marginBottom: 0 }}> 
                                <CheckboxGroup options={plainOptions} defaultValue={['true']}>
                                    {plainOptions.map(option => {
                                        return (
                                            <Checkbox key={option.label}>{option.label}</Checkbox>
                                        )
                                    })}
                                </CheckboxGroup>
                            </FormItem>
                        </Col>
                        </FormItemRow>

I get the result I want to see but the problem of using defaultValue inside of CheckboxGroup component is I get warning saying

Warning: Encountered two children with the same key, `true`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

Seems like defaultValue works as just like key .

I also added checked inside of Check component and assigned boolean value but it does not work either.

How can I safely render a default value inside of checkbox without warning sign?


Solution

  • First of all you used option.label instead of option.name, which gives undefined to all the keys, that's why you are getting warning of same keys.

    <Checkbox key={option.name}>{option.name}</Checkbox>
    

    If you are using CheckboxGroup, you don't need to use Checkbox. You can use CheckboxGroup like this...

    this.state = {
     plainOptions: ["apple", "orange", "banana", "grape"],
     checkedList: ["apple", "banana"] // Default Value
    };
    

    you will get array of values as param of the onChange event

    onChange = (checkedList) => {
      this.setState({ checkedList });
    }
    
    <CheckboxGroup
      options={this.state.plainOptions}
      value={this.state.checkedList}
      onChange={this.onChange}
    />
    

    In above example I used checkedList initial state for default value and assign latest state on onChange event.