Introduction
React renders UI based on states or props. While itβs not possible to use statements like if & else within a JSXs html, I can make use of javascript expression when using the { } parenteces.
Logical AND (&&)
This operator will render the element only when the condition is truthy. But I should avoid using values like 0 since they might render unintentionally.
{isLoggedIn && <Dashboard />}Ternary operator (? : )
Very helpful when I wanna display one or the other values depending on the conditions state.
{isLoading ? <Spinner /> : <Content />}Extracting for cleaner code
Const variable (go to)
Sometimes I will run into conditions that need to be more complex. In that case its always smart, to extract the condition from the html part to the javascript part of a component.
const AppProjectCard = () => {
const message = isError ? 'Error occurred' : 'Success'
return: <p>{message}</p>;Functions (Only when truly complex)
Functions are helpful when there are multiple rendering branches or complex logic is needed.
function renderMessage() {
if (isError) return <Error />
if (isLoading) return <Loading />
return <Success />
}