Skip to content

<WhenMounted> ​

Renders its content only in the browser. During server rendering it renders <:fallback> instead. Use it for anything that needs window, document or other browser APIs, like a chart or a map.

gts
import { WhenMounted } from 'inertia-ember';
import StoreMap from './StoreMap.gts';

<template>
  <WhenMounted>
    <:default><StoreMap /></:default>
    <:fallback><p>Loading the map…</p></:fallback>
  </WhenMounted>
</template>

Arguments ​

None.

Blocks ​

BlockYieldsShows
<:default>nothingIn the browser.
<:fallback>nothingDuring server rendering.

Both are optional. Without <:fallback> the server renders nothing in its place.

Element and attributes ​

None: <WhenMounted> renders only its blocks, with no wrapping element.

Examples ​

A chart that reads the DOM ​

The server sends a sales prop. SalesChart is your own component that draws on a <canvas>:

gts
import type { TOC } from '@ember/component/template-only';
import { WhenMounted, type PageSignature } from 'inertia-ember';
import SalesChart from '../components/SalesChart.gts';

export default <template>
  <h1>Sales</h1>
  <WhenMounted>
    <:default><SalesChart @data={{@props.sales}} /></:default>
    <:fallback><div class='chart-placeholder' style='height: 300px'></div></:fallback>
  </WhenMounted>
</template> satisfies TOC<PageSignature<{ sales: number[] }>>;

A fallback with the same size as the content keeps the page from jumping when the browser takes over.

Content that differs between server and browser ​

Anything computed from the browser, such as the visitor's locale, would make the server HTML disagree with what the browser renders. Rendering it only in the browser avoids that:

gts
import type { TOC } from '@ember/component/template-only';
import { WhenMounted } from 'inertia-ember';

const localTime = (iso: string) => new Date(iso).toLocaleString();

export default <template>
  Posted
  <WhenMounted>
    <:default>{{localTime @publishedAt}}</:default>
    <:fallback>{{@publishedAt}}</:fallback>
  </WhenMounted>
</template> satisfies TOC<{ Args: { publishedAt: string } }>;

Notes ​

  • <WhenMounted> decides once, when it's created: in the browser the content renders straight away, including on the first render that hydrates the server's HTML. Glimmer replaces just that block of the server markup.
  • Without server rendering, <WhenMounted> always shows its content and you don't need it.

Related: Props that arrive later, Server-side rendering.

Released under the MIT License.