x-if Directive

Conditionally add/remove elements from the DOM completely.

What is x-if?

x-if conditionally adds or removes an element from the DOM entirely. It must be used on a <template> tag because that tag does not render anything itself. When the condition becomes false, the element and all its children are destroyed, and event listeners are cleaned up.

When to Use

Use x-if when you want to completely destroy and recreate an element based on a condition – for example, a modal that you want to reset every time it opens, or a heavy component you only want in the DOM when needed.

Example

Code
<div x-data="{ show: false }">
  <button @click="show = !show">Toggle</button>
  <template x-if="show">
    <div>I am completely removed when show is false</div>
  </template>
</div>
Why must I use a template tag?

Because <template> doesn't render anything itself, Alpine can safely replace its content without extra wrapper elements. This keeps your markup clean.

⚠️ Warning

Because x-if removes elements from the DOM, any Alpine components inside will be re‑initialized each time they are added back. This can be expensive for large subtrees.

Helpful? Share this page!↑ Back to top