Conditional rendering is a common pattern in React applications, allowing you to conditionally render components based on certain conditions. While it's a fundamental aspect of React development, it can sometimes lead to complex and verbose code. In this article, we introduce the ConditionalRender component, which simplifies conditional rendering and improves code readability.
Introducing the ConditionalRender Component
The ConditionalRender component is a reusable and versatile tool for handling conditional rendering in your React applications. It provides a cleaner and more concise syntax while offering the flexibility to set rendering limits. Let's dive into how it works and explore some practical examples.
Conditional Rendering in React
Conditional rendering is a common pattern in React applications, allowing you to conditionally render components based on certain conditions. For example, you might want to render a component only if a user is authenticated or render a list of items only if the list has items.
While conditional rendering is a fundamental aspect of React development, it can sometimes lead to complex and verbose code. Let's take a look at an example of conditional rendering in React:
function App({ isAuthenticated }: { isAuthenticated: boolean }) {
return (
<div>
{isAuthenticated ? (
<div>Content to render for authenticated users</div>
) : (
<div>Content to render for non-authenticated users</div>
)}
</div>
);
}
The ConditionalRender Component
The ConditionalRender component is a reusable and versatile tool for handling conditional rendering in your React applications. It provides a cleaner and more concise syntax while offering the flexibility to set rendering limits. Let's dive into how it works and explore some practical examples.
condition
- The condition to evaluate. If the condition is true, the children will be rendered. If the condition is false, the children will not be rendered.limit
- The maximum number of times the children can be rendered. If the limit is 0, the children will not be rendered. If the limit is 1, the children will be rendered once. If the limit is 2, the children will be rendered twice, and so on.children
- The children to render if the condition is true and the limit has not been reached.
The ConditionalRender component is the primary component of the ConditionalRender component. It accepts the following props:
/* eslint-disable react/jsx-no-useless-fragment */
import React, { type ReactNode } from 'react';
interface ConditionalRenderProps {
/**
* @description Condition to render children
* @default false
*/
condition: boolean;
/**
* @description Children to render
* @default null
*/
children: ReactNode;
/**
* @description Limit to render children
* @default undefined
*/
limit?: number; // if limit is 0, then it will not render, otherwise it will render if condition is true
}
function If({ children, condition, limit }: ConditionalRenderProps) {
if (limit !== undefined && limit <= 0) {
return null;
}
// eslint-disable-next-line react/jsx-fragments
return condition ? <React.Fragment>{children}</React.Fragment> : null;
}
function Else({ condition, ...rest }: ConditionalRenderProps) {
return If({ condition: !condition, ...rest });
}
/**
* @description Renders children if condition is true, otherwise null
* @param condition The condition to render children
* @param children The children to render
* @param limit The limit to render children
* @returns The children if condition is true, otherwise null
*/
function ConditionalRender({
condition,
children,
limit,
}: ConditionalRenderProps) {
return (
<If condition={condition} limit={limit}>
{children}
</If>
);
}
ConditionalRender.If = If;
ConditionalRender.Else = Else;
ConditionalRender.defaultProps = {
limit: undefined,
};
export default ConditionalRender;
ConditionalRender.If
The If
component is designed to render its children only if a given condition is met. It also allows you to set a rendering limit, so if the limit is 0, it won't render the children. Here's how you can use it:
ConditionalRender.Else
The Else
component complements the If component by rendering its children when the condition provided to If is false. You can use it as follows:
How It Works
The ConditionalRender component consists of two primary components: If and Else. Here's a brief overview of each:
- If Component
The
If
component is designed to render its children only if a given condition is met. It also allows you to set a rendering limit, so if the limit is 0, it won't render the children. Here's how you can use it:
import ConditionalRender from 'ConditionalRender';
// ...
<ConditionalRender.If condition={someCondition} limit={1}>
{/* Content to render when someCondition is true */}
</ConditionalRender.If>;
- Else Component
The
Else
component complements the If component by rendering its children when the condition provided to If is false. You can use it as follows:
import ConditionalRender from 'ConditionalRender';
// ...
<ConditionalRender.If condition={someCondition}>
{/* Content to render when someCondition is true */}
<ConditionalRender.Else>
{/* Content to render when someCondition is false */}
</ConditionalRender.Else>
</ConditionalRender.If>;
Practical Examples
Let's explore some practical examples to see how the ConditionalRender component can simplify your code.
Example 1: Conditional Rendering Based on User Authentication
In this example, we'll use the ConditionalRender component to render a component based on whether the user is authenticated. We'll also set a limit to prevent the component from rendering more than once.
import ConditionalRender from 'ConditionalRender';
function App({ isAuthenticated }: { isAuthenticated: boolean }) {
return (
<ConditionalRender.If condition={isAuthenticated}>
{/* Content to render for authenticated users */}
</ConditionalRender.If>
<ConditionalRender.Else>
{/* Content to render for non-authenticated users */}
</ConditionalRender.Else>
);
}
Example 2: Limiting the Number of Rendered Items
In this example, we'll use the ConditionalRender component to render a list of items, limiting the number of items rendered to 5.
import ConditionalRender from 'ConditionalRender';
type Item = {
id: number;
name: string;
};
function List({ items }: { items: Item[] }) {
return (
<ul>
{items.map((item, index) => (
<ConditionalRender.If key={item.id} condition={index < 5} limit={5}>
<li>{item.name}</li>
</ConditionalRender.If>
))}
</ul>
);
}
Example 3: Conditional Rendering with a Custom Component
In this example, we'll use the ConditionalRender component to render a custom component based on a condition.
import ConditionalRender from 'ConditionalRender';
function CustomComponent({ data }: { data: any[] }) {
return (
<ConditionalRender condition={data.length > 0}>
{/* Content to render when data has items */}
</ConditionalRender>
);
}
Conclusion
The ConditionalRender component simplifies conditional rendering in React, making your code more readable and maintainable. By providing clean and concise syntax for conditional rendering and the flexibility to set rendering limits, it's a valuable addition to your React toolbox.
To get started with the ConditionalRender component, you can find it on Code Gist and install it via npm or yarn.
Give it a try and experience the benefits of enhanced conditional rendering in your React applications! Happy coding! 🚀
Top comments (0)