React conditional rendering

Note: This post is a details-post for the post: Learning web app development through free online tutorials – Organized Notes and Log, https://raviswdev.blogspot.com/2024/03/learning-web-app-development-through.html .

Conditional Rendering, https://react.dev/learn/conditional-rendering is a useful page in this context. 

Dave Gray Lists and Keys chapter code can be changed to use if else instead of ternery op., as follows:

if (items.length > 0) {
    return (
      <main>
        <ul>
... inner code omitted ...
        </ul>
      </main>
    );
  } else {
    return (
      <main>
        <p style={{ marginTop: "2rem" }}>Your list is empty.</p>{" "}
      </main>
    );
  }

Disadvantage is repetition of code even if it is slightly easier to understand.

...

Logical AND (&&), https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

Javascript Short Circuiting Operators, https://www.geeksforgeeks.org/javascript-short-circuiting/ [AND(&&) short circuit, OR(||) short circuit]

React documentation section “Logical AND operator (&&)” in https://react.dev/learn/conditional-rendering#logical-and-operator- explains how React interprets false and 0 in && operations.

It says, “React considers false as a “hole” in the JSX tree, just like null or undefined, and doesn’t render anything in its place.”
But 0 is rendered! The section states, “However, if the left side is 0, then the whole expression gets that value (0), and React will happily render 0 rather than nothing.”
It states that the following code is a pitfall as it renders 0 (and not nothing) when messageCount is 0:
messageCount && <p>New messages</p>
To render nothing when messageCount is 0, it states that the above code should be written as:
messageCount > 0 && <p>New messages</p>

...






Given below is a test JSX file demonstrating some things that work and some that don’t:

import React from "react";

const JSXTest = () => {
  //   const errorStyle = true;
  // const arr = [0, 1, 2, 3];
  // const arr = [2, 1, 2, 3];
  const arr = [];
  return (
    // <div {errorStyle? style={{color: "red"}} : null}>JSXTest</div> //Fails to compile
    // <div {errorStyle && style={{color: "red"}}}>JSXTest</div> //Fails to compile
    // <div style={errorStyle ? { color: "red" } : null}>JSXTest</div> // compiles and works
    // <div style={errorStyle && { color: "red" }}>JSXTest</div> //compiles and works

    // <div>arr length:{arr.length}</div> //compiles and works
    // <div>{arr.length ? "non-empty array" : "empty array"}</div> //compiles and works
    // <div>{arr.length ? {(arr[0] === 0)? "arr[0] is 0" : "arr[0] is not 0"} : "empty array"}</div> //Fails to compile

    // Below div tag enclosed code fails to compile
    // <div>
    //   {arr.length ? (
    //     {arr[0] === 0 ? "arr[0] is 0" : "arr[0] is not 0"}
    //   ) : (
    //     "empty array"
    //   )}
    // </div> //

    // Below div tag enclosed code compiles and works
    // <div>
    //   {arr.length ? (
    //     //The inner ternary statement below needs to be enclosed in a fragment tag
    //     <>{arr[0] === 0 ? "arr[0] is 0" : "arr[0] is not 0"}</>
    //   ) : (
    //     "empty array"
    //   )}
    // </div>

    // Below code compiles and works
    <div>
      {arr.length
        ? arr[0] === 0
          ? "arr[0] is 0"
          : "arr[0] is not 0"
        : "empty array"}
    </div>
  );
};

export default JSXTest;

...

In react, ternary operator that conditionally returns multiple elements has to enclose them within parentheses as well as fragment tags. So code below fails with error :”Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag …”

      <div>
        {post ? (
            <h3>{post.title}</h3>
            <p>Post datetime: {new Date(post.datetime).toString()}</p>
            <p>{post.body}</p>
        ) : null}
        <Link to="/">Back to Posts List</Link>
      </div>
The fix is as follows:
      <div>
        {post ? (
          <>
            <h3>{post.title}</h3>
            <p>Post datetime: {new Date(post.datetime).toString()}</p>
            <p>{post.body}</p>
          </>
        ) : null}
        <Link to="/">Back to Posts List</Link>
      </div>
Ref: “Ternary Operator” section in Conditionally Render a Component in React, https://stackabuse.com/bytes/conditionally-render-a-component-in-react/

Comments

Archive