How to use switch statement in React
In this article, you are going to learn about how to use the switch statement in React.
In JavaScript, the switch statement is used for making decisions. It works as the if-else statement but there are some syntactical differences. It plays an important role when you need to execute one of many code blocks based on a particular expression of a value or a variable. You often need to use a switch statement while working on a react project and in this article, we will explore this. Before doing so, let’s see a quick example of using the switch statement in JavaScript so that you can recap.
const today = 2
switch (today) {
case 1:
console.log('Today is Saturday')
break
case 2:
console.log('Today is Sunday')
break
case 3:
console.log('Today is Monday')
break
case 4:
console.log('Today is Tuesday')
break
case 5:
console.log('Today is Wednesday')
break
case 6:
console.log('Today is Thursday')
break
case 7:
console.log('Today is Friday')
break
default:
console.log('Invalid Input')
}
// Output : Today is Sunday
Here, we have demonstrated the most common example of a switch statement. It will print a particular output based on the value of the variable and in this case, it is printing Today is Sunday
as the value of the variable is 2
.
You can implement this switch statement in react. Let’s see the below code example where we will implement the above switch statement in react.
import React from 'react'
function App() {
function WeekDays(props) {
switch (props.value) {
case 1:
return <h1>Today is Saturday</h1>
case 2:
return <h1>Today is Sunday</h1>
case 3:
return<h1>Today is Monday</h1>
case 4:
return <h1>Today is Tuesday</h1>
case 5:
return <h1>Today is Wednesday</h1>
case 6:
return <h1>Today is Thursday</h1>
case 7:
return <h1>Today is Friday</h1>
default:
return <h1>Invalid Input</h1>
}
}
return (
<div className="container">
<WeekDays value={2} />
</div>
);
}
export default App
Here, we simply import react and we have declared a function named WeekDays. If you notice, you can see that we are using the return statement instead of using the break statement. Because react provides the option of return statement which works as same as the break statement. Now let’s check the output below to check if things are working perfectly or not.
You can see that we are getting exact same output as before but this time we are using react. If you want to see a different weekday then all you need to do is to pass a different value in between 1 to 7. This is how you can use a switch statement in React and if you need to use a switch statement for a different purpose then you can do so by following this process.