Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save luisjunco/7eab10cd2991fab11a759add4a15b7cc to your computer and use it in GitHub Desktop.
Save luisjunco/7eab10cd2991fab11a759add4a15b7cc to your computer and use it in GitHub Desktop.
React Conditional Rendering - Cheatsheet

A: Element Variables (in your JavaScript)

function MyComponent(){

    let button;
    if (isLoggedIn) {
      button = <LogoutButton />;
    } else {
      button = <LoginButton />;
    }


    return (
      <div>
        {button}
      </div>
    );

}

B: Logical && Operator (in your JSX)

Example:

{errorMessage && <p>{errorMessage}</p>}

C: Ternary Operator (in your JSX)

Example 1:

{isLoggedIn
  ? <LogoutButton />
  : <LoginButton />
}

Example 2:

{recipes.length > 0 
  ? renderRecipes()
  : <p>Sorry, no recipes. Click here to create the first one!</p>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment