Creating Conditional Components in React

Ahmet ÇELİK
2 min readApr 9, 2021

--

There are various ways to conditional rendering in React. In this article, I will talk about how we can do conditional rendering more traceable and readable.

Let’s Make The Component Usage Clear

First rule is divide the components to meaningful and reusable pieces. We can understand the importance of using components correctly with a simple examples below.

On the web page, they both look the same. If every page of web app coded like Component1, it would be so painful for developers.

Custom Conditional Components

Our goal is to understand with the least effort how the Component behaves in which condition. To ensure this, we’ll be inspired by approach of VueJs.

Vuejs has directives for conditional or list rendering like v-if, v-list etc.

For example;

<h1 v-if={false}>Vue is awesome!</h1>
<li v-for="item in items" :key="item.message">
{{ item.message }}
</li>

So, What should we do in React? We can use component properties instead of directives.

1. If Component

I think it doesn’t need to be explained :)

Example usage:

2. SwitchCase Component

Example usage:

3. Ternary Component

I’m not sure if this is necessary. But if you still want to use:

4. Foreach Component (List Rendering)

I like using this component. Because I say “Render this list for each item. I don’t care how you did it”.

Example Usage:

Conclusion

In this article, I talked about to the more readable use of conditional and list rendering operations. I hope that it would be useful for you.

Similar codes for flutter widgets: Conditional Widgets Flutter

--

--

Ahmet ÇELİK

Mobil uygulama geliştirici, gündeme dair konular ve yazılım trendleriyle ilgili özgür bir yazılımcı.