Conditional Rendering

One of the biggest sells for working with templates is the ability to conditional render things. Markup makes it super easy to conditional render anything because of dynamic values.

For a simple example, you can add a function in the template that can quickly check a condition and return different values accordingly.

let count = 5;

html`${() => count % 2 === 0 ? 'even' : 'odd'}`

You can use a function to conditionally return anything you want to be renderer. However, Markup offers a better way.

when helper

Markup exposes a set of helpful helpers and one of them is the when helper which allows you to conditional render anything with better performance and handling.

let count = 5;

const isEven = x => x % 2 === 0;

html`${when(isEven(count), 'even', 'odd')}`

The when helper takes three arguments, and the third one is optional:

when(CONDITION, THEN, ?ELSE):

  • CONDITION: The condition can be a value or, a function that returns a value, and it will be checked if it is TRUTHY or FALSY.
  • THEN: Something to render if the condition is truthy. It can also be a function that returns any value you need.
  • ELSE (optional): Something to render if the condition is falsy. It can also be a function that returns any value you need.

Why use the when helper?

Beyond conditional rendering, the when helper also caches the THEN and ELSE values even when you use them as functions.

This prevents the DOM from being unnecessarily updated when the condition haven't changed (remained truthy or falsy over many changes).

const [count, setCount] = state(0);

html`${
  () => count() > 10 ? html`<p>over 10</p>` : html`<p>under 10</p>`}
`

The above example will render over 10 or under 10 templates on every change even though what you render for over or under 10 looks the same. This would cause unnecessary renders and DOM calculations using plain function instead of when helper because every time the function is called a new template instance is created, which for Markup is different, therefore re-render the DOM to look the same.

With the when helper once the count is over 10 and keeps increasing the DOM will never change. Only when it goes under for the first time.