Search code examples
antdant-design-pro

Conditional rendering of a Form.Item on Ant design


I'm trying to make a form using Ant design v4.0. The display of an Form.Item (Input text) depends of the value of other Form.Item (Radio button group). I'm using form.getFieldValue('fieldname') and it works initially but, when I changed the value of the radio Botton group the field is still showing up.

The code is similar to this

(...)
const [form] = useForm();
(...)
<Form form={form} (...)>
    <Form.Item name="fieldname" initialValues={props.initialValues}>
        // Here it is a radio button group
    </FormItem>
    { form.getFieldValue('fieldname') === 'a_value' && (
        <Form.Item name="a-text-field> 
              // here it is an input text
        </Form.Item>
    )}
</Form>

As I said before, it works with the initial value but if I changed the option it doesn't work. I also try the prop in the field a-text-field but it didn't work

hidden={form.getFieldValue('fieldname') !== 'a_value'}


Solution

  • Check out this example in antd documentation. https://ant.design/components/form/#components-form-demo-control-hooks This doesn't require any state variables. The 'shouldUpdate' prop rerenders the specific form.item.