Rendering Custom Components
Learn how to customize the Formik components.
Customizing the Field
component
By default, the Field
component renders an input field. Any props we pass to it are passed as attributes to the input field. This means we can specify the type
of the input field, for example, by passing it to the type
prop of Field
.
What if we wanted to render a field that is not an input field, for example, a textarea? Or a select dropdown? Or another React component?
Customizing using the as
props
The Field
component accepts an as
prop. This can be the name of an HTML element we want to render or a custom React component. The onChange
, onBlur
, value
, and other props we specify for Field
will be passed to this element or component. Therefore, we must use elements or components that accept these attributes. We could use HTML elements like input
(this is the default), select
, textarea
, or custom React components that accept these props.
An example that uses the HTML select
element is given below:
// renders a select dropdown<Field name="country" as="select" className="country-dropdown"><option value="nigeria">Nigeria</option><option value="india">India</option><option value="burkinafaso">Burkina Faso</option></Field>// The component above renders<select name="country" class="country-dropdown"><option value="nigeria">Nigeria</option><option value="india">India</option><option value="burkinafaso">Burkina Faso</option></select>
Here is an example that uses the HTML textarea
...