Keywords: React | JSX | Conditional Rendering | DRY
Abstract: This article explores how to conditionally include elements in React JSX to avoid code duplication, focusing on the best practice approach where variables set to undefined are ignored by JSX, thereby upholding DRY principles.
Introduction to Conditional Rendering in JSX
In React applications, JSX enables developers to write HTML-like code within JavaScript for dynamic user interfaces. A common requirement is to conditionally render elements based on application state, such as displaying a banner only when it is available.
Core Method: Using Undefined Variables
As highlighted in the best answer, when a variable in JSX is set to undefined, React simply ignores it and does not render any element. This approach effectively prevents duplication of HTML tags, aligning with the DRY (Don't Repeat Yourself) principle.
render: function () {
var banner;
if (this.state.banner) {
banner = <div id="banner">{this.state.banner}</div>;
} else {
banner = undefined; // or simply omit the assignment
}
return (
<div id="page">
{banner}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
In this code example, if this.state.banner is falsy (e.g., null, undefined, or false), the banner variable is set to undefined, and JSX omits rendering any corresponding DOM element, achieving conditional rendering.
Alternative Approaches
Other answers suggest various conditional rendering methods as supplementary references. For instance, using the JavaScript logical AND operator:
{this.state.banner && <div id="banner">{this.state.banner}</div>}
This method leverages JavaScript short-circuit evaluation, rendering the element only when this.state.banner is truthy. However, caution is advised with custom components like If, as their child code is always executed, potentially leading to null pointer exceptions.
Best Practices and Conclusion
To maintain code simplicity and safety, the method of setting variables to undefined is recommended, as it directly utilizes JSX's default behavior without additional components or complex logic. Avoid using custom components that may introduce side effects to ensure application maintainability and performance.