VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/conditional-rendering-component-using-enums-in-reactjs/

⇱ Conditional rendering component using Enums in ReactJS - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Conditional rendering component using Enums in ReactJS

Last Updated : 23 Jul, 2025

In certain scenarios, a ReactJS developer may have to dynamically display or hide components depending on specific conditions. For instance, when creating a To-Do list application, the developer must render tasks if there are pending items; otherwise, they should display a message such as "No pending tasks available."

Prerequisites:

Steps to Create the React Application And Installing Module:

Step 1: To create a new React project, run the below command to your terminal.

npx create-react-app testapp

Step 2: To move inside the project directory, run the below command to your terminal.

cd testapp

Project Structure:

👁 Image

Rendering Component using enum:

Step 1: In javascript, we can create an object with key-value pairs and use it as an enum. Below, you can see the demo of a javascript object with key-value pair.

Syntax:

const Enumobj = {
key: value,
};

Example:

const Enumobj = {
first: <First />,
second: <Second />
};

Step 2: Now, we will make a javascript function that takes a state as a parameter and return a React component based on the state.

Syntax:

function Enum({state}){
return {object[state]};
}

Example:

function Enum({ state }) {
return <div>{Enumobj[state]}</div>;
}

Step 3: Let's embed the 'Enum' function in our 'App' component. While calling the 'Enum' function, we will add state value as props. 

Syntax:

 return (
<div>
<Enum state="Value"></Enum>
</div>
);

Example:

 return (
<div>
<Enum state="first"></Enum>
<Enum state="second"></Enum>
</div>
);

Example: In this example,we will create an enum object first. After that, we will add an 'enum' function to render components according to state value. we will add some basic React code to render on the webpage. The user needs to add the following code to the 'first.js' file.

Steps to Run: The user needs to run beneath the command to the terminal in the current directory to see the output.

 npm start

Output:

👁 Image


Comment