Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux-form v6 show validation error for select field

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 ?

like image 862
Raj Adroit Avatar asked Sep 14 '16 15:09

Raj Adroit


1 Answers

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.

like image 116
Hans Roerdinkholder Avatar answered Oct 26 '22 07:10

Hans Roerdinkholder