Flow: "A valid React element (or null) must be returned."

Created on 26 Dec 2016  路  5Comments  路  Source: facebook/flow

If the render function (in React.Component) will return undefined this will generate runtime error:

invariant.js:38 Uncaught Error: CustomComponent.render():
A valid React element (or null) must be returned. You may have
returned undefined, an array or some other invalid object.

Example code :

type SomePropsType = {
  range: number
};

class CustomComponent extends React.Component {

    props: SomePropsType;

    render(): ?React.Element<*> {
        const {range} = this.props;

    if (range > 100) {
            return (
                <div>some view</div>
            );
        }
    }
}

In function render, flow should not allow to return other type than React.Element<*> or null or false.
This restriction should protect against mentioned runtime error.

Library definitions react

Most helpful comment

Should just be a matter of changing this line from ?React$Element<any> to React$Element<any>|null.

All 5 comments

Should just be a matter of changing this line from ?React$Element<any> to React$Element<any>|null.

The new version of react (16.3) also has this problem.
https://reactjs.org/docs/error-decoder.html?invariant=152&args[]=t

declare type React$Node =
  | void
  | null
  | boolean
  | number
  | string
  | React$Element<any>
  | React$Portal
  | Iterable<React$Node>;
...
declare class React$Component<Props, State = void> {
...
render(): React$Node;
...
}

It would be useful to have a new type of return for the render function that does not have "void" value.

I am passing an array to a child component props, and it seems the child counts the proto of the array as an element and I get the error you mentioned here as a result. Any idea how to fix this?

undefined is not allowed to be returned in render functions or methods

Was this page helpful?
0 / 5 - 0 ratings