Skip to content

Instantly share code, notes, and snippets.

@dmeents
Last active February 19, 2022 22:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmeents/13739fffa28e89470f45f7ee949ab89e to your computer and use it in GitHub Desktop.
Save dmeents/13739fffa28e89470f45f7ee949ab89e to your computer and use it in GitHub Desktop.
Rendering a select field in Redux-Form 6 with validation
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
export const renderSelect = field => (
<div>
<select {...field.input}/>
{field.touched && field.error && <div className="error">{field.error}</div>}
</div>
);
export function validate(formProps) {
const errors = {};
if (!formProps.firstName) {
errors.firstName = 'Please enter a first name';
}
if (!formProps.lastName) {
errors.lastName = 'Please enter a last name';
}
if (!formProps.email) {
errors.email = 'Please enter an email';
}
if (!formProps.phoneNumber) {
errors.phoneNumber = 'Please enter a phone number'
}
if(!formProps.sex) {
errors.sex = 'You must enter your sex!'
}
return errors;
}
import { validate } from '../filepath/form_validation.js';
import { renderSelect } from './form-fields.js';
//render form field, missing all other components
//this is just the select object
<label>Gender:</label>
<Field name="sex" component={renderSelect}>
<option></option>
<option name="male">Male</option>
<option name="female">Female</option>
</Field>
@anthonybrown
Copy link

is this outdated now?

@Adiqq
Copy link

Adiqq commented Jan 2, 2018

It didn't render options, I checked with react 15+, redux-form 7+
This worked for me:

import React from 'react';

export const SelectField = ({
                              input,
                              label,
                              meta: {touched, error},
                              children
                            }) => (
  <div className="field">
    <label className="label">{label}</label>
    <div className="control">
      <div className={
        'select ' + (touched ? (error ? 'is-danger' : 'is-success') : '')
      }>
        <select {...input} >
          {children}
        </select>
        {touched && (error && <p className="help is-danger">{error}</p>)}
      </div>
    </div>
  </div>
);

@keymastervn
Copy link

@Adiqq Your solution works! Thank you
I'm wondering why redux-form author added many useful examples but not this combined select and validation 🤔

@asasouza
Copy link

@Adiqq Thanks! Worked for me.

@sudamchakor
Copy link

sudamchakor commented Mar 27, 2021

This worked for me:

import React from 'react';

export const renderDropDownField = (formValues) => {

    const { input, label, meta, options } = formValues;

    const { touched, error } = meta;

    const formcss = touched ? `form-control is-${error && touched ? 'invalid' : 'valid'}`: 'form-control';

    return (
        <div className="form-group">
            <label htmlFor={input.name}>{label}</label>
            <select {...input} className={formcss} id="exampleFormControlSelect2">
                {
                    options.map((option) => <option value={option.value}>{option.name}</option>)
                }
            </select>
            {(touched && error) ? <div className="help-block text-danger">{error}</div> : ''}
        </div>
    );
}
import React, { Component } from "react";
import { Field, reduxForm } from "redux-form";
import { renderDropDownField } from "../FormBuilder";

class MyForm extends Component {
    
   onFormSubmit = (formValues) => {
        console.log(formValues)
    }

    render() {
        const { handleSubmit } = this.props;
        const categories = [
            {
                value: 'none',
                name: 'Select Category'
            },
            {
                value: 'miss',
                name: 'Miscellaneous'
            },
        ];
        return (
            <div>
                <form onSubmit={handleSubmit(this.onFormSubmit)} className="needs-validation px-5">
                    <Field name="categorie" options={categories} component={renderDropDownField} />
                    <button type="submit" className='btn btn-primary'>Save Changes</button>
                </form>
            </div>
        )
    }
}

const validate = (formValues) => {
    const errors = {};
    if (!formValues.categorie || 'none' === formValues.categorie) {
        errors.categorie = "Please select a valid categorie.";
    }
    return errors;
}


export default reduxForm({
    form: 'blogEditForm',
    validate
})(MyForm);

@vitdeployement
Copy link

vitdeployement commented Feb 19, 2022

Hi everyone,

I am using react 17.0.2
redux 4.1.2
react-redux 7.2.6
and redux-form 8.3.8

Unable to render the dropdown using Field from redux-Form.

Can someone guide me in right direction? Any help would be appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment