Facebook PixelReact Conditional | React JS Tutorial | CodeWithHarry

React Conditional

One of the best things in React is that we can conditionally render elements/components!

&& Operator

This is one way to conditionally render:

function App() {
 
  const loading = true;
 
  return (
    <div className="App">
      {loading && <LoadingGif />}
      {!loading && <Content />}
    </div>
  );
}

Here we are saying if loading is true then show <LoadingGif /> and in the second line, we said !loading so that returns false in this case, so <Content /> will not load and the first statement is true, so <LoadingGif /> will load!

Ternary Operator

What we were doing in the previous example was basically just an if statement. We didn't have else, so we were using if as else too. Let's learn how to do both (if/else)!

The same thing can be done like this:

function App() {
 
  const loading = true;
 
  return (
    <div className="App">
      {loading ? <LoadingGif /> : <Content />}
    </div>
  );
}

We are saying if loading is true then show <LoadingGif />, else show <Content />, simple!

Syntax:

condition ? true : false