if-statements
react support if-statements,but not direct inside jsx.
if-else statement outside function
let a=10;
let msg="";
if(a>5){
msg = "Hello everyone";
}
else{
msg = "bye";
}
function App(){
return(
<h1>{msg}</h1>
)
}
if-else statement inside function
In these ,we can write if-else statement inside function component but outside the JSX.
like:
function App() {
let age = 22;
if (age == 22) {
return <h1>yes</h1>
}
else {
return <h1>no</h1>
}
return (
<h1 className="cd">mahi live here..</h1>
)
}
if-else condition in jsx
we can not use if-else condition directly in jsx. if you write in jsx so condition write in curlibrasis
{}
.we can write like:
function Auser() {
let age = 22;
return (
<div>
{
(()=>{
if(age==22){
return <h1>true age</h1>
}
else{
return <h1>false age</h1>
}
})()
}
<h1>mahi live here..</h1>
</div>
);
}
Ternary operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?
), then an expression to execute if the condition is truthy followed by a colon (:
), and finally the expression to execute if the condition is falsy.
function App() {
let age = 22;
return (
<div>
{
age == 22 ? <h1>true age</h1> : <h1>false age</h1>
}
<h1>mahi live here..</h1>
</div>
);
}
Happy learning..