React-admin CheckboxGroupInput check some checkboxes by default

Viewed 1027

how to make some checkboxes checked by default

    <CheckboxGroupInput
      source="my_junction_table"
      choices={choices}
      optionText={<KioskCheckbox />}
      initialValue={[{ id: 4, checked: true }]}  // don't work
      defaultValue={[{ id: 4, checked: true }]}  // don't work
      options={{ checked: true }}                // check all
      optionValue="id"
    />

with

options={{ checked: true }}

all the checkboxes are checked

with

initialValue={[{ id: 4, checked: true, value: true }]}
defaultValue={[{ id: 4, checked: true }]}

nothing work, I've already see the doc and the code in react-admin repo, can't find anything about that.

3 Answers

The answer from @Shevchuk Slavik is almost worked, just need to replace 'initialValue' prop by 'defaultValue'. Then create 'choices' props like this:

choices={[ { id: 'create', checked: true }, { id: 'update'}, { id: 'approve'} ]}

I have the same problem last week. The initialValue should be an array with identifiers, the object array will not work. I solved it like this:

import React from 'react';
import {CheckboxGroupInput} from 'react-admin';

export const CheckboxGroupInputMod = (props, {checkedProp = 'checked'}) => {
    let initialValue = [];
    props.choices.map(value => {
        if (value[checkedProp]) initialValue.push(value.id);
    })

    return <CheckboxGroupInput {...props} initialValue={initialValue} />;
}

export default CheckboxGroupInputMod;

If the choice list you made is as follows,

you can write down the id of the item you want to select at the initialValue props.

const choices = [
  { id: 'm', name: 'Male' },
  { id: 'f', name: 'Female' }
];

If you want to choose both Male and Female, you can do the following.

<CheckboxGroupInput
  source="my_junction_table"
  choices={choices}
  initialValue={['m', 'f']}
/>
Related