Categories
React Answers

How to use if else inside JSX in React?

Spread the love

To use if else inside JSX in React, we can add them in a function.

For instance, we write

const MyComponent = () => {
  return (
    <div>
      {(() => {
        if (someCase) {
          return <div>someCase</div>;
        } else if (otherCase) {
          return <div>otherCase</div>;
        } else {
          return <div>catch all</div>;
        }
      })()}
    </div>
  );
};

to add the if-else statements in the function.

We call the function immediately so we render the returned value.

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 *