I'm trying to use a <Conditional if={condition}>
component in React, that renders its content only if the condition is true.
I've used the code from here, as mentioned in Broda Noel's response of this question. You also see the code here.
import * as React from 'react';
const Conditional = props => (
!!props.if && props.children
);
class Item extends React.Component {
render() {
const item = { id: 2 };
return (
<>
<h2>Item detail</h2>
{/* Display item.foo.name if `foo` property exists */}
<Conditional if={item.foo}>
{item.foo.name}
</Conditional>
</>);
}
}
export default Item;
It fails with the error:
Uncaught TypeError: Cannot read property 'name' of undefined
I know I can also use {item.foo && item.foo.name}
, but when the code becomes more complex, I find the use of Conditional
more readable. And most important, I would really like to understand what happens here.
Why does React render the content of the Conditional, even is the condition is false? Is there a way to change the Conditional component to make it work in this case?
I'm using React 16.4.1, with typescript.