Hi Developers,
In this we will learn switch case statement in React. We will see two methods for executing the switch statement.
In the first example we will declare the userType in the function and the we use that in the switch statement in the return function
src/App.js
import React from 'react';
function App() {
const userType = 'Admin';
return (
<div className="container">
<h1>React Switch Case Condition Example - ITSolutionsGuides</h1>
{(() => {
switch (userType) {
case 'Admin':
return (
<div>You are a Admin.</div>
)
case 'Manager':
return (
<div>You are a Manager.</div>
)
default:
return (
<div>You are a User.</div>
)
}
})()}
</div>
);
}
export default App;
----------------------------------------------------
Output:
You are a Admin.
In this method we declare the switch case as a functional component
1) when the SwitchCase component is called in the return function it will send the value through props
2) Then the functional component collects the data through props and executes the switchcase and returns the output
src/App.js
import React from 'react';
function App() {
function SwitchCase(props) {
switch(props.value) {
case 'Admin':
return 'You are a Admin.';
case 'Manager':
return 'You are a Manager.';
default:
return 'You are a User';
}
}
return (
<div className="container">
<h1>React Switch Case Condition Example - ITSolutionsGuides</h1>
<SwitchCase value={'Admin'} />
</div>
);
}
export default App;
----------------------------------------------------
Output:
You are a Admin.
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides