In v6 of redux-form we can show the errors for normal input fields like following
We can create custom renderField like this
const renderField = ({ input, label, type, meta: { touched, error } }) => (
<div>
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type}/>
{touched && error && <span>{error}</span>}
</div>
</div>
)
And in the form, just we can use that custom renderField
<Field name="username" type="text" component={renderField} label="Username"/>
Now i need to know, How we can do this same for select field, and how should we pass dropdown options to this custom renderFields, Any idea to create custom renderField for select ?
If you don't mind some code duplication, you could do it like this:
const renderSelectField = ({ input, label, type, meta: { touched, error }, children }) => (
<div>
<label>{label}</label>
<div>
<select {...input}>
{children}
</select>
{touched && error && <span>{error}</span>}
</div>
</div>
)
Consume it in the form:
<Field name="username" component={renderSelectField} label="Username">
{ mySelectOptions.map(option => <option value={option.value}>{option.text}</option>) }
</Field>
You can see that passing the options to a select is done through props.children
, exactly the same as when you would use the Field
component with component="select"
.
If you don't want the duplication, you could try to make the original renderField
a bit smarter instead. For example, you could see if children
contains option-tags, and if so, render the <select>
instead of the input
.
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