Andy Andy - 4 years ago 151
React JSX Question

Conditional rendering and warning when using propTypes validation

I have a React component that expects children on input. PropTypes are set as following:

static propTypes = {
children: PropTypes.arrayOf(PropTypes.element).isRequired
};


However I receive warning when inline conditional turns false, i.e:

{isLoggedIn && <div>You are logged in</div>}



Warning: Failed prop type: Invalid prop
children[0]
of type
boolean
supplied to
WelcomeComponent
, expected a single ReactElement.


Documentation does not really help.
https://facebook.github.io/react/docs/conditional-rendering.html

Answer Source

This is because of how the && operator works. If the first expression is falsy, the result of its evaluation will be the return value of the operator. You can read about it in details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators.

In your case it will return false when the user is not logged in, and you still expect to get a valid React element, which it does not satisfy.

You can see the logic that PropTypes use to check whether the received props are OK (for the element check) right here: https://github.com/facebook/react/blob/master/src/isomorphic/classic/element/ReactElement.js#L378. In your case the typeof false === 'object' will fail. Then https://github.com/facebook/react/blob/master/src/isomorphic/classic/types/ReactPropTypes.js#L252 this method will print the warning.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download