bkula
bkula

Reputation: 559

React stateless functional component should return null but receiving error

I have a simple component to display invalid form entries, which obviously should only render a message when said form entries are invalid. As far as I can tell, I used the conditional return statements correctly, but I'm still getting an error.

Here's the component:

import React from 'react'; import PropTypes from 'prop-types';

function FormErrors ({formErrors}) {
    Object.keys({formErrors}).map((field, i) => {
        if ({formErrors}[field].length > 0) {
            return (
                <p key={i}>{field} {formErrors[field]}</p>
            )
        } else {
            return null;
        }
    })
}

export default FormErrors;

The props being passed in:

formErrors: {email: '', password: ''};

And the error message I'm receiving:

Invariant Violation: FormErrors(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

Upvotes: 1

Views: 1697

Answers (1)

FuzzyTree
FuzzyTree

Reputation: 32392

Nothing was returned from render.

You're missing a return

function FormErrors ({formErrors}) {
    return Object.keys({formErrors}).map((field, i) => {
    // ^^ add this return
        if ({formErrors}[field].length > 0) {
            return (
                <p key={i}>{field} {formErrors[field]}</p>
            )
        } else {
            return null;
        }
    })
}

Upvotes: 6

Related Questions