React JSX Question

Pass boolean to expected react-element component props in material-ui list-item

I am new in React and may be my question will sound stupid...

I have a material-ui list-item component, and I want to make an edit icon was available only to the content owner.

For example:

var rightAction = (this.props.canEdit)?<IconButton><NavigationClose /></IconButton>:false;

<ListItem
//properties...
rightIconButton={righAction}
/>


Of course, if you go down to the page content is not the owner, at his console, we will see this error:


Failed prop type: Invalid prop
rightIconButton
of type
boolean

supplied to
ListItem
, expected a single ReactElement.


The question:

How can we transfer or not to transfer the property, depending on the conditions?

Thank you!

Answer

If you pass undefined to a prop, it is equivalent to not passing it at all.

So just change your conditional to:

var rightAction = this.props.canEdit ? <IconButton><NavigationClose /></IconButton> : undefined;

You could also make it simpler to read (imho) by breaking it up:

var button = (<IconButton><NavigationClose /></IconButton>);
var rightAction = this.props.canEdit ? button : undefined;
Comments