Lesson 17-Preact Conditional Rendering and Loops

Conditional rendering and loop rendering in Preact are essential techniques for building dynamic user interfaces. Conditional rendering allows you to display or hide components or elements based on state, while loop rendering enables you to render a series of elements from a dataset. These techniques enhance Preact’s flexibility and expressiveness.

Conditional Rendering

Conditional rendering lets you show or hide components or elements based on conditions. In Preact, you can use JavaScript’s conditional expressions (ternary operator) or logical operators to achieve this.

Using the Ternary Operator

import { h } from 'preact';

function Greeting({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome back!</p> : <p>Please sign up.</p>}
    </div>
  );
}

Using the && Operator

import { h } from 'preact';

function Greeting({ isLoggedIn, username }) {
  return (
    <div>
      {isLoggedIn && <p>Welcome back, {username}!</p>}
    </div>
  );
}

Loop Rendering

Loop rendering is used to render multiple elements based on a data collection. In Preact, the map function is commonly used for this purpose.

Using the map Function

import { h } from 'preact';

function NumberList({ numbers }) {
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>
      {number}
    </li>
  );

  return (
    <ul>{listItems}</ul>
  );
}

Key Attribute

When rendering loops, assigning a unique key to each element is critical. This helps Preact identify which elements have been added, moved, or removed, improving rendering efficiency.

Using key

import { h } from 'preact';

function NumberList({ numbers }) {
  return (
    <ul>
      {numbers.map((number) => (
        <li key={number.toString()}>
          {number}
        </li>
      ))}
    </ul>
  );
}

Combining Conditions and Loops

In real-world applications, you often need to combine conditional rendering and loop rendering to render different types of elements based on conditions.

Combining Conditions and Loops

import { h } from 'preact';

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map((todo) => (
        todo.completed ? (
          <li key={todo.id} style={{ textDecoration: 'line-through' }}>
            {todo.text}
          </li>
        ) : (
          <li key={todo.id}>{todo.text}</li>
        )
      ))}
    </ul>
  );
}

Performance Optimization

When handling large datasets, using key properly and avoiding unnecessary re-renders can significantly boost performance. Additionally, leveraging shouldComponentUpdate or React.memo can prevent unneeded component updates.

Share your love