GICT knowledge base
React Switch Case Statement – Beginner’s Guide
Published
Switch case is a fundamental programming concept that you will learn regardless of the languages you work on. Switch case is like multiple if-else condition but simpler to manage and good to work with in many cases where there might be multiple values in a specific variable and we want to handle it differently based on the value. Think of it like a vending machine. You press button A1, you get chips. You press button B2, you get soda. Switch case works the same way.
In this tutorial, we will use the syntax of React/Javascript to understand the concept. However, only the syntax will change when the programming language changes, concept stays the same.
Basic Example
function getMessage(mood) {
switch (mood) {
case 'happy':
return 'I am smiling';
case 'sad':
return 'I am crying';
case 'angry':
return 'I am mad';
default:
return 'I dont know';
}
}
Why Use a Switch Case?
Instead of writing this:
if (day === 'monday') {
return 'Work day';
}
if (day === 'tuesday') {
return 'Work day';
}
if (day === 'saturday') {
return 'Weekend';
}
You can write this:
switch (day) {
case 'monday':
return 'Work day';
case 'tuesday':
return 'Work day';
case 'saturday':
return 'Weekend';
default:
return 'Unknown day';
}
Different Methods to Use Switch Case
Method 1: Function Inside Component
You can make a function inside your React component. This way you can use the same code many times. Just call the function when you need it.
function App() {
const [weather, setWeather] = useState('sunny');
const getWeatherMessage = () => {
switch (weather) {
case 'sunny':
return 'Wear sunglasses';
case 'rainy':
return 'Take umbrella';
case 'cloudy':
return 'Maybe rain';
default:
return 'Check weather';
}
};
return (
<div>
<h1>{getWeatherMessage()}</h1>
<button onClick={() => setWeather('sunny')}>Sunny</button>
<button onClick={() => setWeather('rainy')}>Rainy</button>
<button onClick={() => setWeather('cloudy')}>Cloudy</button>
</div>
);
}
Method 2: Direct in JSX
You can put switch case directly in your HTML code. This shows different things on the page right away.
function App() {
const [page, setPage] = useState('home');
return (
<div>
{(() => {
switch (page) {
case 'home':
return <h1>Welcome Home!</h1>;
case 'about':
return <h1>About Us</h1>;
case 'contact':
return <h1>Contact Us</h1>;
default:
return <h1>Page Not Found</h1>;
}
})()}
<button onClick={() => setPage('home')}>Home</button>
<button onClick={() => setPage('about')}>About</button>
<button onClick={() => setPage('contact')}>Contact</button>
</div>
);
}
Method 3: Using Object Alternative
You can use an object instead of a switch case. This is faster for simple things. Just make an object with all your options.
function App() {
const [animal, setAnimal] = useState('cat');
const animalSounds = {
cat: 'Meow',
dog: 'Woof',
cow: 'Moo',
bird: 'Tweet'
};
const animalColors = {
cat: 'Orange',
dog: 'Brown',
cow: 'Black and White',
bird: 'Blue'
};
return (
<div>
<h1>Animal: {animal}</h1>
<h2>Sound: {animalSounds[animal] || 'No sound'}</h2>
<h2>Color: {animalColors[animal] || 'No color'}</h2>
<button onClick={() => setAnimal('cat')}>Cat</button>
<button onClick={() => setAnimal('dog')}>Dog</button>
<button onClick={() => setAnimal('cow')}>Cow</button>
<button onClick={() => setAnimal('bird')}>Bird</button>
</div>
);
}
Method 4: Multiple Cases Same Action
Sometimes many options do the same thing. You can group them together without writing the same code again.
function App() {
const [day, setDay] = useState('monday');
const getDayType = () => {
switch (day) {
case 'monday':
case 'tuesday':
case 'wednesday':
case 'thursday':
case 'friday':
return 'Work day - Go to office';
case 'saturday':
case 'sunday':
return 'Weekend - Time to relax';
default:
return 'Not a valid day';
}
};
return (
<div>
<h1>{getDayType()}</h1>
<button onClick={() => setDay('monday')}>Monday</button>
<button onClick={() => setDay('tuesday')}>Tuesday</button>
<button onClick={() => setDay('saturday')}>Saturday</button>
<button onClick={() => setDay('sunday')}>Sunday</button>
</div>
);
}
Method 5: Switch with Conditions
You can use switch with numbers and ranges. This checks if something is bigger or smaller than a value.
function App() {
const [score, setScore] = useState(85);
const getGrade = () => {
switch (true) {
case score >= 90:
return 'A - Excellent';
case score >= 80:
return 'B - Good';
case score >= 70:
return 'C - Average';
case score >= 60:
return 'D - Below Average';
default:
return 'F - Failed';
}
};
return (
<div>
<h1>Score: {score}</h1>
<h2>Grade: {getGrade()}</h2>
<button onClick={() => setScore(95)}>95</button>
<button onClick={() => setScore(85)}>85</button>
<button onClick={() => setScore(75)}>75</button>
<button onClick={() => setScore(55)}>55</button>
</div>
);
}
Method 6: Switch for Component Rendering
You can use switch case to show different pages or sections. Only one section shows at a time.
function App() {
const [userType, setUserType] = useState('guest');
const renderUserDashboard = () => {
switch (userType) {
case 'admin':
return (
<div>
<h2>Admin Panel</h2>
<p>You can manage everything</p>
<button>Delete Users</button>
<button>View Reports</button>
</div>
);
case 'user':
return (
<div>
<h2>User Dashboard</h2>
<p>Welcome back user</p>
<button>View Profile</button>
<button>Edit Settings</button>
</div>
);
case 'guest':
return (
<div>
<h2>Guest Access</h2>
<p>Please login to see more</p>
<button>Login</button>
<button>Register</button>
</div>
);
default:
return <div>Something went wrong</div>;
}
};
return (
<div>
<nav>
<button onClick={() => setUserType('admin')}>Admin</button>
<button onClick={() => setUserType('user')}>User</button>
<button onClick={() => setUserType('guest')}>Guest</button>
</nav>
{renderUserDashboard()}
</div>
);
}
Simple Rules
- Write break after each case
- Always add default at the end
- Use switch when you have many options
- Keep each case simple
- Check one thing against many values
When to Use Switch Case
- User types like admin, user, guest
- App status like loading, done, error
- Colors, themes, languages
- Days of week, months
- Grades, scores, levels
Switch case makes your code clean and easy to read when you have many choices to handle.
