User7354632781
User7354632781

Reputation: 2264

React: what is the correct syntax for boolean check

I have a boolean prop in react and i am trying to use it as shown below:

const MyComponent = ({ prop1, prop2, isBoolean }) => {
...do something..
return (
 if (isBoolean) ? (do this) : (do that)
}

So i am saying if isBoolean is true then do this else do that. is this the correct syntax?

Upvotes: 2

Views: 16691

Answers (5)

Kyle Richardson
Kyle Richardson

Reputation: 5645

If you want to do conditional rendering inside the return ( expression ) you will need to use a ternary operator.

const MyComponent = ({ prop1, prop2, isBoolean }) => {
    // ...do something..
    return (
       { isBoolean ? (do this) : (do that) }
    );
};

You could also perform your condition before the return statement as follows:

const MyComponent = ({ prop1, prop2, isBoolean }) => {
    // ...do something..

    const DOMToRender = isBoolean ? this : that;

    return (
       { isBoolean ? (do this) : (do that) }
    );
};

You could also repleace const DOMToRender = isBoolean ? this : that; with and if/else statement.

Upvotes: 2

alechill
alechill

Reputation: 4502

And if it is possible to be undefined at any point (ie by default) you can force it into a boolean value for the ternary by the double bang!!

return !!isBoolean ? (do this) : (do that)

Upvotes: 0

Zahlex
Zahlex

Reputation: 648

No, either simply:

isBoolean ? this : that

Or, for more complex (multi-line) code:

if (isBoolean) {
  this
} else {
  that
}

Upvotes: 0

Bartek Fryzowicz
Bartek Fryzowicz

Reputation: 6674

No, it's not correct syntax in JS. You've mixed if statement and tenary operator in one statement. Correct syntax is either:

  • If statement

    if (isBoolean) {
      //do this
    } else {
      //do that
    }
    
  • or tenary operator

    isBoolean ? expression1 : expression2;
    

Upvotes: 0

kind user
kind user

Reputation: 41893

If you want to use ternary operator, you have to remove if keyword.

isBoolean ? (do this) : (do that)

Then it will be indeed a proper syntax.

Upvotes: 0

Related Questions