ReactJS — Easy Conditional Rendering

According to https://reactjs.org/docs/conditional-rendering.html

Creator : Burak Kebapci On : Pexels

In my perspective :

If the component is a stateful component, and you want to render different element according to the states inside the component.You might also have some event handler to interact with user activities, and the states changes which causes a render update.Then you could consider conditional rendering.

How to start?

Prepare three things : States / Methods / Components

Let’s dive into it — -A BubbleControl Component.

First thing first, I’ll provide whole codes on my codepen!!!

Section 1 : Define the state and bind the methods /Define the event handlers

Give a default value to the state and bind the methods inside the constructor.The event handlers from line8 to line13 help you to handle user activities.(User want to turn on the light bulb, then we set the state to true)

Section 2 : render and return what you want to display on the DOM

The render() method is the only required method in a class component.

When called, it should examine this.props and this.state and return one of the following types:

You can use variable to store the element(line16).The variable will help you to conditionally render specific component(line18 or line 20).

Section 3 : Define components

Define parent components for their children in section 2.

Section 4 : Don’t miss the HTML and CSS

Demo : https://www.loom.com/share/0ef0d8c0d5164314b096c796fc098df3