{{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.
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.
| Argument | Type | Default | Description |
|---|---|---|---|
href | string | UrlMethodPair | the element's href attribute | Where to go: a URL, or a { url, method } pair whose method wins over method. On an <a>, the href attribute is kept in sync. |
method | Method | 'get' | The request method, in either case. |
data | RequestPayload | {} | 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. |
headers | Record<string, string> | {} | Extra request headers. |
replace | boolean | false | Replace the current history entry instead of adding one. |
preserveScroll | boolean | 'errors' | ((page) => boolean) | false | Keep the scroll position. |
preserveState | boolean | 'errors' | ((page) => boolean) | false for GET, true otherwise | Keep the page component's local state. |
preserveUrl | boolean | false | Keep the current URL. |
only | string[] | [] | Partial reload: ask only for these props. |
except | string[] | [] | Partial reload: every prop but these. |
reset | string[] | [] | Props to replace instead of merging (for merge props such as paginated lists). |
async | boolean | false | An async visit, which doesn't cancel other visits and isn't cancelled by them. |
prefetch | boolean | 'hover' | 'click' | 'mount' | LinkPrefetchOption[] | false | Prefetch the page: on hover (true means 'hover'), on mouse down, as soon as the element is inserted, or a combination. |
cacheFor | CacheForOption | 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. |
cacheTags | string | string[] | [] | Tags for the prefetched response, to invalidate it later. |
viewTransition | boolean | ((transition: ViewTransition) => void) | false | Run the page swap in a view transition. |
component | string | Render this page component right away, an Inertia instant visit. | |
instant | boolean | false | With an href pair that names a component, render that component right away. |
pageProps | Record<string, unknown> | ((currentProps, sharedProps) => Record<string, unknown>) | null | null | Props 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 atargetother than_selfare left to the browser, so "open in new tab" keeps working. - Prefetch.
'hover'prefetches after the pointer rests on the element forprefetch.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-loadingattribute. - DOM events. Each callback also dispatches a
CustomEventon the element, sooncan listen to it:
| Event | detail | Notes |
|---|---|---|
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
A link styled as your own component
Keep the <a> so the browser treats it as a link (middle click, "copy link"), and add the modifier.
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.
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
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.
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
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>
}.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 settypeon a<button>; inside a<form>, writetype='button'so it doesn't submit the form.