Reputation: 29
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.
Upvotes: 0
Views: 625
Reputation: 2387
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>)
Upvotes: 1
Reputation: 392
If you want to use if
then you have to use ternary operator
because if
in java scripts are statements, not expressions.
const Welcome = () => {
const isLoggedIn = true;
return (<div>{isLoggedIn ? <p>Welcome!</p> : <p>Please Login</p>}</div>);
}
Upvotes: 2