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>
<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.
The name props in Formik can use lodash-like dot paths to reference nested Formik values. This means that you do not need to flatten out your form's values anymore.
Using Formik's handleChange The handleChange method updates the form values based on the input's name attribute that was changed.
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>
<button type="reset" className="btn btn-secondary">
Reset
</button>
</Form>
)}
</Formik>;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With