How to Write an else if Structure Using React JSX?

Sometimes, we want to write an else if structure using React JSX.

In this article, we’ll look at how to write an else if structure using React JSX.

Write an else if Structure Using React JSX

To write an else if structure using React JSX, we can write regular if-else statements in React components.

For instance, we write:

import React from "react";

const Condition = ({ conditionA, conditionB }) => {
  if (conditionA) {
    return <span>Condition A</span>;
  } else if (conditionB) {
    return <span>Condition B</span>;
  } else {
    return <span>Neither</span>;
  }
};

export default function App() {
  return (
    <>
      <Condition conditionA />
      <Condition conditionB />
      <Condition />
    </>
  );
}

to create the Condition component that takes the conditionA and conditionB props.

In the component, we check if conditionA is true, then we return a span with ‘Condition A’ as its content.

If conditionB is true, then we return a span with ‘Condition B’ as its content.

Otherwise, we return a span with ‘Neither’ as its content.

In App, we add Condition with the props.

Then we see:

Condition ACondition BNeither

displayed.

Conclusion

To write an else if structure using React JSX, we can write regular if-else statements in React components.