How to use Switch Statement Inside a React Component?
Last Updated :
25 Sep, 2024
When the switch statement is used within a React component it can greatly improve the readability and structure of the code. The logic of a switch statement can be clear and concise. This avoids complex and difficult nested if-else blocks.
This leads to more maintainable and better-organized code. In large projects it is necessary.
Steps to Create React App
Step 1: You will start a new project using the following command
npx create-react-app newproject
Step 2: Now go to your react-rating folder by typing the given command in the terminal.
cd newproject
npm start
Project Structure:
Project StructureUpdated Dependencies:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
},
Syntax:
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// Add more cases as needed
default:
// Code to be executed if expression doesn't match any case
}
Example 1: In the below example we will use the switch statement inside a react component.
JavaScript
// App.jsx
import React, { useState } from "react";
function GreetingComponent() {
const [timeOfDay, setTimeOfDay] = useState("morning"); // State variable
const renderGreeting = () => {
switch (timeOfDay) {
case "morning":
return <h1>Good Morning!</h1>;
case "afternoon":
return <h1>Good Afternoon!</h1>;
case "evening":
return <h1>Good Evening!</h1>;
default:
return <h1>Hello!</h1>;
}
};
return (
<div>
{renderGreeting()} {/* Render different greetings based on timeOfDay */}
<button onClick={() => setTimeOfDay("morning")}>Morning</button>
<button onClick={() => setTimeOfDay("afternoon")}>Afternoon</button>
<button onClick={() => setTimeOfDay("evening")}>Evening</button>
</div>
);
}
export default GreetingComponent;
Output:
Example 2: In the below example we will use the switch statement.
JavaScript
// App.jsx
import React, { useState } from "react";
function StatusComponent() {
const [status, setStatus] = useState("loading");
// State variable for status
const renderStatusMessage = () => {
switch (status) {
case "loading":
return <p>Loading... Please wait.</p>;
case "success":
return <p>Data loaded successfully!</p>;
case "error":
return <p>Error loading data. Please try again.</p>;
default:
return <p>Unknown status.</p>;
}
};
return (
<div>
<h1>Status Checker</h1>
{renderStatusMessage()} {/* Render message based on status */}
<button onClick={() => setStatus("loading")}>Set to Loading</button>
<button onClick={() => setStatus("success")}>Set to Success</button>
<button onClick={() => setStatus("error")}>Set to Error</button>
</div>
);
}
export default StatusComponent;
Output:
Conclusion
Using a switch statement in React components improves readability, maintainability, and organization. It provides a more structured and efficient way to handle multiple conditions by avoiding the complexity of multiple if-else statements. It makes your code clearer and easier to extend in the future.