React 18

Last Updated: 9/24/2023

Conditional Rendering

Using if else

if (items.length === 0) 
	return (
		<p>No items found</p>
	)
else
  return (
    <ul className="list-group">
      {items.map((item) => (
        <li className="list-group-item">{item}</li>
      ))}
    </ul>
  );

Using variables

let content;
if (items.length === 0) 
	content = <p>No items found</p>;
else
  content = (
    <ul className="list-group">
      {items.map((item) => (
        <li className="list-group-item">{item}</li>
      ))}
    </ul>
  );

return (
  <>
    <h1>List</h1>
    {content}
  </>
);

Using Ternary

return (
  <>
    <h1>List</h1>
    {items.length === 0 ? <p>No Items</p>: null}
  </>
);

Using Logical And&&

return (
  <>
    <h1>List</h1>
    { items.length === 0 && "No Items" }
  </>
);

Using Functions

const getMessage = () => {
	return items.length === 0 ? <p>No Items</p>: null;
}
return (
  <>
    <h1>List</h1>
    {getMessage()}
  </>
);