Search code examples
javascriptreactjsjsxreact-admin

How to dynamically show or hide form fields depending on the state of a BooleanInput field in react-admin?


I need to build a complex edit form with react-admin. The form has a variety of yes/no sliders made with the BooleanInput component of react-admin. If the user sets the slider to "yes", further form fields should appear dynamically, which refer thematically to the slider. How do I query the status of the BooleanInput component or would this task be solved in react in a different way?

<BooleanInput source="yesno" label="show or hide fields" />
<AutocompleteArrayInput source="probably_hidden1" label="show or hide me" choices={[
        { id: 'one', name: '1' },
        { id: 'two', name: '2' },
        { id: 'three', name: '3' }
]} />
<TextInput multiline source="text" label="show or hide me too" />

Solution

  • I found out: It can be done using FormDataConsumer like this:

    <BooleanInput source="yesno" label="show or hide fields" />
    <FormDataConsumer>
        {({ formData, ...rest }) => formData.yesno && <div>
            <AutocompleteArrayInput source="yesno" label="show or hide fields" choices={[
                { id: 'one', name: '1' },
                { id: 'two', name: '2' },
                { id: 'three', name: '3' }
            ]} {...rest} />
            <TextInput multiline source="text" label=""show or hide me too" {...rest} />
        </div>
        }
    </FormDataConsumer>
    

    See: https://marmelab.com/react-admin/Inputs.html#hiding-inputs-based-on-other-inputs