Golinmarq
Golinmarq

Reputation: 1006

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'}

Upvotes: 8

Views: 15921

Answers (2)

Manoj kumar
Manoj kumar

Reputation: 44

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.

Upvotes: 2

Chanandrei
Chanandrei

Reputation: 2421

it's because if the radio input changed, it does not change the form.item value so doing form.getFieldValue('fieldname') will not work. You may use a state instead and use onValuesChange prop of the form:

const [radioValue, setRadioValue] = useState("a_value");
const [form] = useForm();
(...)

const handleFormValuesChange = (changedValues) => {
    const fieldName = Object.keys(changedValues)[0];

    if(fieldName === "a-text-field"){
        const value = changedValues[fieldName];
        setRadioValue(value)
    } 
}

<Form form={form} onValuesChange={handleFormValuesChange}>
    <Form.Item name="fieldname" initialValues={radioValue}>
        // Here it is a radio button group
    </FormItem>
    { radioValue === 'a_value' && (
        <Form.Item name="a-text-field'> 
              // here it is an input text
        </Form.Item>
    )}
</Form>

here is the link of working sample

Upvotes: 3

Related Questions