Thursday, January 30, 2025
Google search engine
HomeLanguagesConditional rendering component using Enums in ReactJS

Conditional rendering component using Enums in ReactJS

In some situations, React Js developer needs to render and hide components based on the particular condition. For example, while building a To-do list app, the developer needs to render tasks if any pending task is available otherwise they need to show a message like “There is no pending task available.”

There are several methods to render components conditionally in react Js such as if-else, and ternary operator, etc. If only 2 to 3 components are available to render conditionally, developers can use if-else or switch case method. If there are more than 3 components available to render conditionally, if-else becomes complex. So, developers should use enums to keep code clean.

In this tutorial, we are going to learn that how developers can render components conditionally using enums. To start with enums, users need to create a new react project.

Creating react project:

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

Now, you have created react app successfully. 

Next, users need to create 2 to 3 components in our project. Create a ‘components‘ folder inside the ‘src‘ folder. Also, create the first.js and second.js files inside the components folder.

Project structure: It should look like the below image.

In this file, 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.

Filename: first.js

Javascript




import React, { Component } from 'react';
 
// Some basic code to render first component
class First extends Component {
    render() {
        return (
            <div>
                <h1 style={{ color: "green" }}>GeeksForGeeks</h1>
                <h2>This is a first component</h2>
            </div>
        );
    }
}
 
export default First;


 
In this file, we will add some basic React code that is different from the first component. So, we can know which component is rendering on the screen. Edit the ‘second.js’ file and add the below code inside it.

Filename: second.js

Javascript




import React, { Component } from 'react';
 
// some basic code to render second component
class Second extends Component {
    render() {
        return (
            <div>
                <h1 style={{ color: "green" }}>GeeksForGeeks</h1>
                <h2>This is a second component.</h2>
            </div>
        );
    }
}
 
export default Second;


 
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>
);

Filename: App.js

In the App.js file, we will create an enum object first. After that, we will add an ‘enum’ function to render components according to state value. At last, we will edit the ‘App‘ component and call the ‘enum‘ function inside the component to render it conditionally. The user needs to add the below code to the ‘App.js‘ file.

Filename: App.js

Javascript




import React, { Component } from 'react';
import Second from './components/second'
import First from './components/first'
 
// Creating enum object
const Enumobj = {
    first: <First />,
    second: <Second />
};
 
// Creating enum function to return
// Particular component according to state value
function Enum({ state }) {
    return <div>{Enumobj[state]}</div>;
}
 
// Call enum function inside the App component
class App extends Component {
    render() {
        return (
            <div>
                <Enum state="first"></Enum>
                <Enum state="second"></Enum>
            </div>
        );
    }
}
 
export default App;


 
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:

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments