Search code examples
reactjsredux-form

redux-form (version 6.4.3) does not display errors


below is the code for the redux-form. Everything works beautifully with the redux store but I can not display the error messages in the span element.

import React from 'react'
import { Button } from 'react-bootstrap'
import { Field, reduxForm } from 'redux-form'

const validate = (values) => {
    const errors = {}
    if (!values.firstname) {
        errors.firstname = 'Required'
    }
    return errors
}

const renderInput = (field) => (
    <div>
        <label>{field.placeholder}</label>
        <div>
            <input {...field.input}/>
            {field.error && <span>{field.error}</span>}
        </div>
    </div>
)

@reduxForm({
    form: 'addUserForm',
    validate
})

export default class CreateUserForm extends React.Component {
    render() {
        const {addUser, handleSubmit} = this.props
        return (
            <form onSubmit={handleSubmit(addUser)}>
                <Field type="text" placeholder="First name" component={renderInput} name="firstname" />
                <Button type="submit" className="btn btn-success">Submit</Button>
            </form>
        )
    }
}

I can clearly see that the validation function works (see screen shot below)

enter image description here

but there is nothing in the <span></span> element, which means the field.error has no value. I also don't get an error message at all.

Does someone know what's going on here?

Thanks, Thomas


Solution

  • Your renderInput is incomplete.

    The official document shows:

    const renderField = ({ input, label, type, meta: { touched, error, warning } }) => (
      <div>
        <label>{label}</label>
        <input {...input} placeholder={label} type={type}/>
        {
          touched && (
            (error && <span>{error}</span>) || (warning && <span>{warning}</span>)
          )
        }
      </div>
    )
    

    Observe the object, parameters passed to renderField: meta: { touched, error, warning }

    With that regards, shouldn't your renderInput be:

    const renderInput = (field) => (
      <div>
        <label>{field.placeholder}</label>
        <div>
          <input {...field.input}/>
          {field.meta.error && <span>{field.meta.error}</span>}
        </div>
      </div>
    )
    

    Missing => field.meta.error