Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
59 lines (48 loc) · 1.5 KB

File metadata and controls

59 lines (48 loc) · 1.5 KB
Copy raw file
Download raw file
Outline
Edit and raw actions
id ternary-operation
sidebar_label Ternary operation
title Ternary Operation
description Ternary operation | React Patterns, techniques, tips and tricks in development for Ract developer.
keywords
ternary operation
react ternary operation
reactpatterns
react patterns
reactjspatterns
reactjs patterns
react
reactjs
react techniques
react tips and tricks
version Ternary operation
image /img/reactpatterns-cover.png

Syntax

You can make your if-else statement more concise by using a ternary operation.

condition ? expr1 : expr2

For example

Imagine you have a toggle to switch between two modes, edit and view, in your component. The derived condition is a simple boolean. You can use the boolean to decide which element you want to return.

function Item({ item, mode }) {
  const isEditMode = mode === 'EDIT'

  return (
    <div>
      { isEditMode
          ? <ItemEdit item={item} />
          : <ItemView item={item} />
      }
    </div>
  )
}

If your blocks in both branches of the ternary operation are getting bigger, you can use parentheses.

function Item({ item, mode }) {
  const isEditMode = mode === 'EDIT'

  return (
    <div>
    { isEditMode ? 
      (
        <ItemEdit item={item} />
      ) : 
      (
        <ItemView item={item} />
      )
    }
    </div>
  );
}

The ternary operation makes the conditional rendering in React more concise than the if-else statement. It is simple to inline it in your return statement.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.