okumu justine
okumu justine

Reputation: 368

Using OR operator in React js conditional rendering

I want to conditionally render a button based on two conditions. Am not really sure if am doing it the right way.

But i get this error This condition will always return 'true' since the types '"started"' and '"cancelled"' have no overlap.ts(2367) where the red underline is.

Am using React js with typescript enter image description here

Upvotes: 1

Views: 10342

Answers (3)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

When you are checking for multiple values, you can simplify with includes method

{ !["started", "cancelled"].includes(journey) && <Button> Cancel Journey </Button> }

Alternatively

{ journey === "stopped" && <Button> Cancel Journey </Button> }

or

{ ["stopped"].includes(journey) && <Button> Cancel Journey </Button> }

Upvotes: 2

Dhanuka Perera
Dhanuka Perera

Reputation: 1813

If there are only two options in your condition like "stared" and "cancelled" you can add ternary operator.

{journey === "stared" ? <Button>Journey Started</Button> : <Button>Journey Cancelled </Button>}

But if more options like ("stared","cancelled","completed","any other")

  {journey === "stared" && <Button>Journey Started</Button> }
  {journey === "cancelled" && <Button>Journey cancelled</Button> }
  {journey === "completed" && <Button>Journey completed</Button> }

This is an optional thing, It's a best practice not to use strings directly in conditions. Better you define them as type, or enum,(If using typescript with React) or just costs;

const STARTED = "started"
const COMPLETED = "completed"
const CANCELED = "canceld"

const journey = STARTED // Or anything the matches with the requirement.


{journey === STARTED ? <Button>Journey Started</Button> : <Button>Journey Cancelled </Button>}

Upvotes: 0

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

You have a logical error. A variable can not have two values at the same time which means that journey !== "started" || journey !== "cancelled" will always be true.

You probably want to use journey === "started" in order to display the Cancel Button

Upvotes: 0

Related Questions