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
of type
supplied to
, expected a single ReactElement.

Documentation does not really help.

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:

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: In your case the typeof false === 'object' will fail. Then this method will print the warning.

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