Home » Web Development » JavaScript » React.js » Conditional Rendering React

About Yatin

Avatar photo
An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Conditional Rendering React

Welcome readers, in this tutorial, we will understand how to render conditional content in a react-js application.

1. Introduction

React is a flexible javascript library responsible for building reusable UI components. It is an open-source component-based frontend library responsible only for the view part of an application and works in a virtual document object model. But before that let us take a look at the differences between angular and react –

AngularReact
Complete frameworkLibrary
Object-oriented programmingExtension to the javascript library and its internal architecture is based on jsx
Based on the model view controller and real document object modelBased on the virtual document object model

1.1 Setting up dependencies

To play with react let us set up some of the required dependencies.

1.1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

1.2.2 Setting up reactjs project

Once the Nodejs setup is successful we will use the below command to install the react library and set up the project. Do note that the npx package is available with the npm 5.2 version and above.

Create project structure

$ npx create-react-app rendering-conditional-contect-reactjs-app

The above command will take some time to install the react library and create a new project named – rendering-conditional-contect-reactjs-app as shown below.

Fig. 2: Project structure

2. Component splitting in react-js application

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

2.1 Setting up the react code

To understand a practical implementation let us go through some hands-on exercises.

2.1.1 Creating Toggle component

Create a folder named components in the src folder and add the Toggle component to the folder. The props keyword will be used to read the values from the parent component and perform a certain actions in Toggle component.

  • The button will show/hide the content based on the isVisibleProperty

Toggle.js

import React from "react";

const Toggle = (props) => {
  const toggleVisibilityHandler = props.toggleVisibility;
  const isVisibleProperty = props.isVisible;

  return (
    <div>
      <button onClick={toggleVisibilityHandler}>
        {isVisibleProperty ? "Hide Details" : "Show Details"}
      </button>
      {isVisibleProperty && (
        <div>
          <p>When the button is clicked this text is shown...</p>
        </div>
      )}
    </div>
  );
};

export default Toggle;

2.1.2 Creating implementation file

In the App.js component we have used the react state to set the default value of the isVisible flag. The toggleVisibility will be responsible to toggle the flag value upon the button click.

App.js

import { useState } from "react";
import "./App.css";
import Toggle from "./components/Toggle";

function App() {
  const [isVisible, setIsVisible] = useState(false);
  const toggleVisibility = () => setIsVisible(!isVisible);

  return (
    <div className="App">
      <h2>Rendering conditional content in reactjs</h2>
      <Toggle
        isVisible={isVisible}
        toggleVisibility={toggleVisibility}
      ></Toggle>
    </div>
  );
}

export default App;

3. Run the setup

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run start

The application will be started on the default port. In case the application does not get started on the default port you can change the port number as per your requirement. I have changed the default port to 2000.

Fig. 3: Application run

4. Demo

The application will be started in the default browser as shown below and the home page with a button will be shown.

Fig. 4: Application demo

Click on the button. The hidden content and the updated button text will be shown.

Fig. 5: Hidden content shown

On clicking the button again the content will be hidden and the button text will be reverted to the original. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we created a react application and understood conditional content rendering in react-js. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to understand conditional content rendering in a react application.

Download
You can download the full source code of this example here: Conditional Rendering React

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments