Categories
React Answers

How to Use the Switch Statement Inside a React Component?

Spread the love

Sometimes, we want to use switch statements inside a React component.

In this article, we’ll look at how to use switch statements inside a React component.

Use the Switch Statement Inside a React Component

We can use switch statements inside a React component as we do with plain JavaScript.

For instance, we can write:

import React from "react";

const Foo = ({ val }) => {
  switch (val) {
    case "bar":
      return "bar";
    default:
      return "foo";
  }
};

export default function App() {
  return (
    <>
      <Foo val="bar" />
      <Foo val="abc" />
    </>
  );
}

We have the Foo component that takes the val prop.

And we use the switch statement to render the content we want to render with the return statement.

So if we set val to bar we render bar .

Otherwise, we render foo .

Conclusion

We can use switch statements inside a React component as we do with plain JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *