Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing javascript in JSX with expression

I am trying to understand the concept of writing expression in JSX but unable to understand that how is not javascript in curly braces an expression?

const Welcome()=>{
  const isLoggedIn = true;
  return(
    <div>
      {
        if(isLoggedIn){
          <p>Welcome!</p>
        }else{
          <p>Please Login</p>
        }
      }
    </div>  
  );
}

Please guide me either when we assign a value isLoggedIn is true then validation happens, if value is true then it prints Welcome otherwise please log in.

Please tell me how is this a statement and not an expression.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

if statements in JavaScript are, by definition, statements, and not expressions.

An expression can be considered as code that you can assign to a variable:

const myVar = 2 + 2;
const otherVar = someFuncCall();

Here, 2 + 2 and someFuncCall() are expressions because they can be assigned to a variable.

An if statement can’t be assigned to a variable:

const invalidCode = if (someCondition) { "ABC"; } // This code won't run

You can use a ternary operator instead, which can be used to create expressions just like any other operators (e.g. + operator):

const Welcome = () => {
  const isLoggedIn = true;
  return(
    <div>
      {isLoggedIn ? (<p>Welcome!</p>) : (<p>Please Login</p>)}
    </div>  
  );
}

This code works, because it’s possible to assign this result to a variable:

const myJsx = isLoggedIn ? (<p>Welcome!</p>) : (<p>Please Login</p>)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading