JSX - if else condition
https://react-cn.github.io/react/tips/if-else-in-JSX.html
return (
<section>
<h1>Color</h1>
<h3>Name</h3>
<p>{this.state.color || "white"}</p>
<h3>Hex</h3>
<p>
{(() => {
if (this.state.color === "red") {
return "#FF0000";
} else if (this.state.color === "grees") {
return "#00FF00";
}
....
})()}
</p>
</section>
);
If you prefer a more “inline” aesthetic, define immediately-invoked function expressions inside your JSX:
return (
<section>
<h1>Color</h1>
<h3>Name</h3>
<p>{this.state.color || "white"}</p>
<h3>Hex</h3>
<p>
{(() => {
switch (this.state.color) {
case "red": return "#FF0000";
case "green": return "#00FF00";
case "blue": return "#0000FF";
default: return "#FFFFFF";
}
})()}
</p>
</section>
);
Another approach is, we can use Short Circuit Evaluation
import { useState } from 'react';
const ShortCircuitOverview = () => {
// falsy
const [text, setText] = useState('');
// truthy
const [name, setName] = useState('susan');
const codeExample = text || 'hello world';
// can't use if statements
return (
<div>
{/* {if(someCondition){"won't work"}} */}
<h4>Falsy OR : {text || 'hello world'}</h4>
<h4>Falsy AND {text && 'hello world'}</h4>
<h4>Truthy OR {name || 'hello world'}</h4>
<h4>Truthy AND {name && 'hello world'}</h4>
{codeExample}
</div>
);
};
export default ShortCircuitOverview;
More examples of Short Circuit Evaluation
import { useState } from 'react';
const ShortCircuitExamples = () => {
// falsy
const [text, setText] = useState('');
// truthy
const [name, setName] = useState('susan');
const [user, setUser] = useState({ name: 'john' });
const [isEditing, setIsEditing] = useState(false);
return (
<div>
{/* content inside element */}
<h2>{text || 'default value'}</h2>
{/* toggle element */}
{text && (
<div>
<h2> whatever return</h2>
<h2>{name}</h2>
</div>
)}
{/* more info below */}
{!text && <h4>also works</h4>}
{/* toggle component */}
{user && <SomeComponent name={user.name} />}
<h2 style={{ margin: '1rem 0' }}>Ternary Operator</h2>
{/* inside element */}
<button className='btn'>{isEditing ? 'edit' : 'add'}</button>
{/* toggle elements or components */}
{user ? (
<div>
<h4>hello there user {user.name}</h4>
</div>
) : (
<div>
<h2>please login</h2>
</div>
)}
</div>
);
};
const SomeComponent = ({ name }) => {
return (
<div>
<h4>hello there, {name}</h4>
<button className='btn'>log out</button>
</div>
);
};
export default ShortCircuitExamples;