1

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

3
  • So when do you want to show the button? Commented Jul 22, 2020 at 8:39
  • This has nothing to do with React, it's a simple logic error. Your condition will always be true, since journey will always be different from either "started" or "cancelled", no matter which value it actually has. You probably want to replace that || with another && Commented Jul 22, 2020 at 8:42
  • when journey !== "started" and journey !== "cancelled" is true, because it has about three states (started, cancelled and stopped) Commented Jul 22, 2020 at 8:43

3 Answers 3

2

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> }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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>}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.