DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

React Tips — Conditionals

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

React is the most used front end library for building modern, interactive front end web apps. It can also be used to build mobile apps.

In this article, we’ll look at some tips for rendering conditional expressions and statements.

Conditionals IIFEs

Adding conditional expressions in JSX has some tricky parts. If we want to render conditional statements inside JSX code, we can only use expressions. Therefore, we can’t use if blocks inside JSX easily.

One good use for immediately-invoked function expressions (IIFEs) is to put conditional statements inside an anonymous function and then call it immediately.

For instance, we can write the following code to do that:

import React from "react";

export default function App() {
  const [num, setNum] = React.useState(1);
  return (
    <div className="App">
      <button onClick={() => setNum(Math.ceil(Math.random() * 5))}>Draw</button>
      <p>
        {(() => {
          if (num === 1) {
            return "one";
          } else if (num === 2) {
            return "two";
          } else if (num === 3) {
            return "three";
          } else if (num === 4) {
            return "four";
          } else if (num === 5) {
            return "five";
          }
        })()}
      </p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we have the IIFE with the if block:

(() => {
 if (num === 1) {
   return "one";
 } else if (num === 2) {
    return "two";
 } else if (num === 3) {
    return "three";
 } else if (num === 4) {
    return "four";
 } else if (num === 5) {
    return "five";
 }
})()
Enter fullscreen mode Exit fullscreen mode

It’s an expression so, it can be inside JSX code. We can also substitute the if...else with one switch in our example.

Also, we can move the function out of the JSX and call it from inside the JSX code as follows:

import React from "react";

export default function App() {
  const [num, setNum] = React.useState(1);
  const getResult = () => {
    if (num === 1) {
      return "one";
    } else if (num === 2) {
      return "two";
    } else if (num === 3) {
      return "three";
    } else if (num === 4) {
      return "four";
    } else if (num === 5) {
      return "five";
    }
  };
  return (
    <div className="App">
      <button onClick={() => setNum(Math.ceil(Math.random() * 5))}>Draw</button>
      <p>{getResult()}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The code above is cleaner than putting a big IIFE inside the JSX code.

&& Operator

To conditionally display something inside a piece of JSX code, we can use the && operator as follows:

import React from "react";

export default function App() {
  const [show, setShow] = React.useState(false);

  return (
    <div className="App">
      <button onClick={() => setShow(show => !show)}>Toggle</button>
      <p>{show && <span>foo</span>}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we have the show boolean which controls whether <span>foo</span> is shown. It’s shown if show is true because of short-circuiting evaluation.

If show is true , then the 2nd operand will be evaluated since the && operator returns true if both operands returns true .

Ternary Operator

Another case if we want to display one thing if a condition is true and displays something else if the same condition is false . We can do that with the ternary operator, which returns one thing if the given condition is true and returns something else is the given condition is false .

For instance, we can make a toggle that shows ‘foo’ and ‘bar’ when then button is clicked as follows:

import React from "react";

export default function App() {
  const [show, setShow] = React.useState(false);

  return (
    <div className="App">
      <button onClick={() => setShow(show => !show)}>Toggle</button>
      <p>{show ? <span>foo</span> : <span>bar</span>}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Separate Presentational Component

Finally, we can write return statements to conditionally return the JSX code that we want to see as the result. We can move the code that’s inside our IIFE to another component and then we can pass the result that’s generated from clicking the button and then return the things we want to display according to other prop’s value.

For instance, we can write the following code to do that:

import React from "react";

const Result = ({ num }) => {
  if (num === 1) {
    return <p>one</p>;
  } else if (num === 2) {
    return <p>two</p>;
  } else if (num === 3) {
    return <p>three</p>;
  } else if (num === 4) {
    return <p>four</p>;
  } else if (num === 5) {
    return <p>five</p>;
  }
};

export default function App() {
  const [num, setNum] = React.useState(1);
  return (
    <div className="App">
      <button onClick={() => setNum(Math.ceil(Math.random() * 5))}>Draw</button>{" "}
      <Result num={num} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we moved our if...else blocks to another component. This is cleaner since Result is a presentational component that takes the num prop and displays what’s there. The App component has the main logic.

The code above is an example of clean separation between the container and presentational components. Container components have the logic, and presentational components display what’s given.

Conclusion

Conditionals can be written in many ways in React components that use JSX. For the simplest conditionals like conditionally displaying a single element or component, we can use the && operator.

If we want to be able to toggle between 2 components and elements depending on a single condition, we can use the ternary operator.

To add if...else statements in our code, we can add a function to an existing component to return the result either as an IIFE inside the JSX code, a separate function inside the component or in a separate component that’s only used for presentation.

Top comments (0)