11
votes

I have a form written in Formik. I need to show/hide a 'text' field depending on the value (option) selected of the 'select' field. How can I achieve this?

<Formik
    initialValues={{transactionCategory, name}}
    onSubmit={this.onSubmit}
    validateOnChange={false}
    validateOnBlur={false}
    validate={this.validate}
    enableReinitialize={true}
>
    {(props) => (
        <Form>

            <fieldset className="form-group">
                <label>Category</label>
                <Field name="transactionCategory" component="select">
                    <option value="Admission">Admission</option>
                    <option value="Class_Fee">Class Fee</option>
                    <option value="Staff_Payment">Staff Payment</option>
                    <option value="Other">Other</option>
                </Field>
            </fieldset>

            <fieldset className="form-group">
                <label>Name</label>
                <Field className="form-control" type="text" name="name"/>
            </fieldset>

            <button className="btn btn-success" type="submit">Save</button>
            &nbsp;
            <button type="reset" className="btn btn-secondary">Reset</button>
        </Form>
    )}
</Formik>

When I select the value 'Other' from the 'Category' options, the 'Name' field should be hidden.

2

2 Answers

17
votes

Conditionally render name field by using transactionCategory value

<Formik
    initialValues={{ transactionCategory, name }}
    onSubmit={this.onSubmit}
    validateOnChange={false}
    validateOnBlur={false}
    validate={this.validate}
    enableReinitialize={true}
>
    {props => (
        <Form>
            <fieldset className="form-group">
                <label>Category</label>
                <Field name="transactionCategory" component="select">
                    <option value="Admission">Admission</option>
                    <option value="Class_Fee">Class Fee</option>
                    <option value="Staff_Payment">Staff Payment</option>
                    <option value="Other">Other</option>
                </Field>
            </fieldset>

            {props.values.transactionCategory !== "Other" && (
                <fieldset className="form-group">
                    <label>Name</label>
                    <Field className="form-control" type="text" name="name" />
                </fieldset>
            )}

            <button className="btn btn-success" type="submit">
                Save
            </button>
            &nbsp;
            <button type="reset" className="btn btn-secondary">
                Reset
            </button>
        </Form>
    )}
</Formik>;
3
votes

write onSelect/onchange event of option and based on the Option's selected value. Update the state field.

this.setState({isName:true})

now you can use this.state.isName in condition rendering to show and hide the field.