Sign Up

Conditional rendering

Occasionally you will want to conditionally render components. You can attach a if={...} attribute to any component in order to render it based on the result of the expression.

Conditional rendering is primarily used with user preferences.

If

To conditionally render a components, add the if={ ... } attribute to it:

<Card if={ 2 > 4 }>
  I won't be shown
</Card>

<Card if={ true }>
  But I will!
</Card>

else

You can combine an if component with an else component.

<Card if={ false }>
  I won't be rendered
</Card>
<Card else>
  But I will!
</Card>

elseif

You can finally also use elseif for more complex scenarios.

<Card if={ false }>
  I won't be rendered
</Card>
<Card elseif={ false }>
  I also won't be rendered
</Card>
<Card else>
  But I will!
</Card>

A note about sibling components

Components with if and else must be sibling elements. When exactly elements are siblings can sometimes be unintuitive due to how Markdown and our components system handles inline and block components.

You may encountered an error like this when dealing with if/else statements:

Example error when matching 'if' is not found for an 'else'
Conditional should start with an "if"

   55 │
   56 │ <Button else href="/">Second</Button>

                └─ Replace "else" with "if"

This may mean that the elements aren't siblings.

Sibling inline elements

When the start and end tag of the component (or HTML element) are on the same line, they're parsed as inline components. This means that they get wrapped in a block level component, which in this case is a paragraph tag.

These two buttons are siblings:

<Button href="/">First</Button>
<Button href="/">Second</Button>

But these aren't.

<Button href="/">First</Button>

<Button href="/">Second</Button>

In the first example, the document is parsed as a single paragraph, as follows:

- paragaph
  - Button
  - Button

The second one is parsed as two paragraphs due to the additional newline, causing the buttons to no longer be next to each other:

- paragaph
  - Button
- paragaph
  - Button

Sibling block elements

When the start and end tag of the component (or HTML element) are on different lines, they're parsed as block components. You can take the button examples above and make them block components as like this:

<Button href="/">
  First
</Button>

<Button href="/">
  Second
</Button>

With block-level components, blank lines are optional. The two elements will be siblings with or without the blank line, and won't be wrapped in a paragraph tag.

Was this page helpful?