Skip to content

{{inertia}} ​

Turns an element of your own into an Inertia link: a click visits the URL without a full page load. It takes the same options as <Link>, which is built on it.

gts
import { inertia } from 'inertia-ember';

<template>
  <a href='/posts' {{inertia}}>Posts</a>
  <button type='button' {{inertia href='/logout' method='post'}}>Log out</button>
</template>

Arguments ​

All named. Every one is optional.

ArgumentTypeDefaultDescription
hrefstring | UrlMethodPairthe element's href attributeWhere to go: a URL, or a { url, method } pair whose method wins over method. On an <a>, the href attribute is kept in sync.
methodMethod'get'The request method, in either case.
dataRequestPayload{}Data to send. For GET it's merged into the URL's query string (and the <a>'s href).
queryStringArrayFormat'brackets' | 'indices''brackets'How arrays in data are written into the query string.
headersRecord<string, string>{}Extra request headers.
replacebooleanfalseReplace the current history entry instead of adding one.
preserveScrollboolean | 'errors' | ((page) => boolean)falseKeep the scroll position.
preserveStateboolean | 'errors' | ((page) => boolean)false for GET, true otherwiseKeep the page component's local state.
preserveUrlbooleanfalseKeep the current URL.
onlystring[][]Partial reload: ask only for these props.
exceptstring[][]Partial reload: every prop but these.
resetstring[][]Props to replace instead of merging (for merge props such as paginated lists).
asyncbooleanfalseAn async visit, which doesn't cancel other visits and isn't cancelled by them.
prefetchboolean | 'hover' | 'click' | 'mount' | LinkPrefetchOption[]falsePrefetch the page: on hover (true means 'hover'), on mouse down, as soon as the element is inserted, or a combination.
cacheForCacheForOption | CacheForOption[]the prefetch.cacheFor default (30 s); 0 when prefetch is only 'click'How long a prefetched response stays fresh: ms, or a string such as '1m'. Two values for stale-while-revalidate.
cacheTagsstring | string[][]Tags for the prefetched response, to invalidate it later.
viewTransitionboolean | ((transition: ViewTransition) => void)falseRun the page swap in a view transition.
componentstringRender this page component right away, an Inertia instant visit.
instantbooleanfalseWith an href pair that names a component, render that component right away.
pagePropsRecord<string, unknown> | ((currentProps, sharedProps) => Record<string, unknown>) | nullnullProps for the instantly rendered component until the server answers.

It also takes the visit callbacks, called with Inertia's arguments: onBefore, onBeforeUpdate, onStart, onProgress, onSuccess, onError, onCancel, onFinish, onHttpException, onNetworkError, onFlash, onCancelToken, onPrefetching and onPrefetched. Returning false from onBefore cancels the visit.

The options and callbacks are Inertia core's; see links, manual visits and prefetching in its docs. Defaults such as prefetch.cacheFor and prefetch.hoverDelay (75 ms) are set with createInertiaApp's defaults.

Behavior ​

  • Clicks. A click visits the URL. On an <a>, clicks with a modifier key (Ctrl, Cmd, Shift, Alt), with a mouse button other than the main one, or on a link with a target other than _self are left to the browser, so "open in new tab" keeps working.
  • Prefetch. 'hover' prefetches after the pointer rests on the element for prefetch.hoverDelay, and stops if it leaves sooner. 'click' prefetches on mouse down (or Enter, and Space on a <button>) and visits on release. 'mount' prefetches once, when the element is inserted.
  • Loading state. While a visit started by the element is in flight, the element has a data-loading attribute.
  • DOM events. Each callback also dispatches a CustomEvent on the element, so on can listen to it:
EventdetailNotes
before{ visit }Cancelable: event.preventDefault() cancels the visit.
start{ visit }
progress{ progress }Upload progress.
success{ page }
error{ errors }Validation errors.
httpException{ response }
networkError{ error }
flash{ flash }
cancel{}
cancel-token{ token }
finish{ visit }
prefetching{ visit }
prefetched{ response }

The events don't bubble: listen on the element that has the modifier.

Examples ​

Keep the <a> so the browser treats it as a link (middle click, "copy link"), and add the modifier.

gts
import Component from '@glimmer/component';
import { inertia, page } from 'inertia-ember';

export default class NavLink extends Component<{
  Element: HTMLAnchorElement;
  Args: { href: string };
  Blocks: { default: [] };
}> {
  get active() {
    return page.url.startsWith(this.args.href);
  }

  <template>
    <a
      href={{@href}}
      class='nav-link {{if this.active "active"}}'
      aria-current={{if this.active 'page'}}
      {{inertia prefetch=true}}
      ...attributes
    >{{yield}}</a>
  </template>
}

A button that posts, after confirming ​

A visit that changes data belongs on a <button>. onBefore returning false stops it.

gts
import Component from '@glimmer/component';
import { inertia } from 'inertia-ember';

export default class DeleteButton extends Component<{ Args: { url: string } }> {
  confirm = () => window.confirm('Delete this post?');

  <template>
    <button type='button' {{inertia href=@url method='delete' preserveScroll=true onBefore=this.confirm}}>
      Delete
    </button>
  </template>
}

Without onBefore, a before listener works too: {{on 'before' this.maybeCancel}} and event.preventDefault().

Prefetch what the user will open next ​

gts
import { array } from '@ember/helper';
import { inertia } from 'inertia-ember';

<template>
  {{! As soon as it renders, kept fresh for a minute }}
  <a href='/dashboard' {{inertia prefetch='mount' cacheFor='1m'}}>Dashboard</a>

  {{! On hover and on mount }}
  <a href='/inbox' {{inertia prefetch=(array 'hover' 'mount') cacheTags='inbox'}}>Inbox</a>
</template>

Reload part of the page ​

only asks the server for some props, and data adds query parameters. Here a tab reloads the orders prop and keeps the rest of the page as it is.

gts
import { array, hash } from '@ember/helper';
import { inertia } from 'inertia-ember';

<template>
  <nav>
    <a
      href='/orders'
      {{inertia data=(hash status='open') only=(array 'orders') preserveState=true preserveScroll=true replace=true}}
    >Open</a>
    <a
      href='/orders'
      {{inertia data=(hash status='shipped') only=(array 'orders') preserveState=true preserveScroll=true replace=true}}
    >Shipped</a>
  </nav>
</template>

The href attribute becomes /orders?status=open, so opening it in a new tab works too.

Show that a visit is in flight ​

gts
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { array } from '@ember/helper';
import { on } from '@ember/modifier';
import { inertia } from 'inertia-ember';

export default class Refresh extends Component {
  @tracked lastRefresh: Date | null = null;

  get time() {
    return this.lastRefresh?.toLocaleTimeString();
  }

  done = () => (this.lastRefresh = new Date());

  <template>
    <button
      type='button'
      class='refresh'
      {{inertia href='/stats' only=(array 'stats') preserveState=true}}
      {{on 'success' this.done}}
    >Refresh</button>
    {{#if this.time}}<small>Updated {{this.time}}</small>{{/if}}
  </template>
}
css
.refresh[data-loading] {
  opacity: 0.5;
  cursor: progress;
}

Notes ​

  • The other adapters only have <Link>. The modifier lets any element be a link without a wrapper component, and <Link> is the modifier on an <a> or <button>.
  • Put it on an <a> or a <button>. Other elements get the click handling but not the keyboard behavior or the semantics of a link.
  • {{inertia}} doesn't set type on a <button>; inside a <form>, write type='button' so it doesn't submit the form.

Related: Links, <Link>, <Form>.

Released under the MIT License.