Don't check the 'array.length' property when conditionally rendering elements |
To avoid rendering empty arrays, you should explicitly check the array for items using 'array.length > 0'
CheckId | RCT010106 |
---|---|
TypeName | LengthPropertyCheckRule |
Severity | Error |
Type | React component |
When rendering elements conditionally in React, elements that are undefined, null, true or false are excluded from rendering. This however doesn't apply to the 0, which would be rendered. To avoid rendering empty arrays, you should explicitly check the array for items using array.length > 0.
Bad practice
export class Tags extends React.Component {
render() {
return (
<div>
{this.props.tags.length && `${this.props.tags.join(', ')}`}
</div>
);
}
}
render() {
return (
<div>
{this.props.tags.length && `${this.props.tags.join(', ')}`}
</div>
);
}
}
Good practice
export class Tags extends React.Component {
render() {
return (
<div>
{this.props.tags.length > 0 && `${this.props.tags.join(', ')}`}
</div>
);
}
}
render() {
return (
<div>
{this.props.tags.length > 0 && `${this.props.tags.join(', ')}`}
</div>
);
}
}
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.