### Manual SSR Entry Point Example (Vue)
Source: https://inertia-rails.dev/guide/server-side-rendering
Example of an SSR entry point file for manual setup in a Vue 3 application.
```javascript
import createServer from '@inertiajs/vue3/server'
createServer((page) =>
createInertiaApp({
page,
render: renderToString,
resolve: (name) => {
const pages = import.meta.glob('../pges/**/*.vue')
return pages[`../pages/${name}.vue`]()
},
setup({ App, props, plugin }) {
return createSSRApp({
render: () => h(App, props),
}).use(plugin)
},
}),
)
```
--------------------------------
### Basic Polling Setup
Source: https://inertia-rails.dev/guide/polling
Use the `usePoll` hook to start polling the server every 2000 milliseconds. This is the simplest way to set up polling.
```javascript
import { usePoll } from '@inertiajs/vue3'
usePoll(2000)
```
--------------------------------
### React SSR Setup with Custom Entry Point
Source: https://inertia-rails.dev/guide/server-side-rendering
Example of setting up Inertia SSR for React using a custom entry point, including rendering and component resolution.
```javascript
import createServer from '@inertiajs/react/server'
import ReactDOMServer from 'react-dom/server'
createServer((page) =>
createInertiaApp({
page,
render: ReactDOMServer.renderToString,
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.jsx')
return pages[`../pages/${name}.jsx`]()
},
setup: ({ App, props }) => ,
}),
)
```
--------------------------------
### Svelte Manual Setup
Source: https://inertia-rails.dev/guide/client-side-setup
Illustrates the manual Inertia.js setup for Svelte, demonstrating the `resolve` function for component resolution and the `setup` function for mounting the Svelte application.
```javascript
import { createInertiaApp } from '@inertiajs/svelte'
import { mount } from 'svelte'
createInertiaApp({
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.svelte')
return pages[`../pages/${name}.svelte`]()
},
setup({ el, App, props }) {
mount(App, { target: el, props })
},
})
```
--------------------------------
### Svelte SSR Setup with Custom Entry Point
Source: https://inertia-rails.dev/guide/server-side-rendering
Example of setting up Inertia SSR for Svelte using a custom entry point, including rendering and component resolution.
```javascript
import createServer from '@inertiajs/svelte/server'
createServer((page) =>
createInertiaApp({
page,
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.svelte')
return pages[`../pages/${name}.svelte`]()
},
setup({ App, props }) {
return render(App, { props })
},
}),
)
```
--------------------------------
### Install Inertia.js Vite Plugin
Source: https://inertia-rails.dev/llms-full.txt
Install the optional Inertia.js Vite plugin for simplified SSR setup and component resolution shorthand.
```bash
npm install @inertiajs/vite@^3.0
```
--------------------------------
### Logging Visit Start with the 'start' Event
Source: https://inertia-rails.dev/llms-full.txt
The 'start' event fires when a request to the server has begun. Use this to log the URL of the initiated visit. This event is not cancelable.
```js
import { router } from '@inertiajs/vue3'
router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
```jsx
import { router } from '@inertiajs/react'
router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
```js
import { router } from '@inertiajs/svelte'
router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
--------------------------------
### React SSR Entry Point Example
Source: https://inertia-rails.dev/guide/server-side-rendering
A complete example of an SSR entry point for a React application.
```jsx
import createServer from '@inertiajs/react/server'
import ReactDOMServer from 'react-dom/server'
createServer((page) =>
createInertiaApp({
page,
render: ReactDOMServer.renderToString,
resolve: (name) => {
const pages = import.meta.glob('../pges/**/*.jsx')
return pages[`../pages/${name}.jsx`]()
},
setup: ({ App, props }) => ,
}),
)
```
--------------------------------
### Controller Redirect Example
Source: https://inertia-rails.dev/guide/redirects
Example of a controller action that redirects after creating a user. It demonstrates redirecting to a standard GET endpoint or back to a form with errors.
```ruby
class UsersController < ApplicationController
def create
user = User.new(user_params)
if user.save
redirect_to users_url
else
redirect_to new_user_url, inertia: { errors: user.errors }
end
end
private
def user_params
params.expect(user: [:name, :email])
end
end
```
--------------------------------
### Production Build and SSR Server Start
Source: https://inertia-rails.dev/guide/server-side-rendering
For production, build both bundles and start the SSR server using Node.js.
```bash
npm run build
node public/assets-ssr/inertia.js
```
--------------------------------
### Complete Inertia.js Custom Loading Indicator Example
Source: https://inertia-rails.dev/guide/progress-indicators
This comprehensive example integrates NProgress with Inertia.js, including start delay, progress updates for file uploads, and handling of different visit completion states (completed, interrupted, cancelled).
```javascript
import NProgress from 'nprogress'
import { router } from '@inertiajs/vue3'
let timeout = null
router.on('start', () => {
timeout = setTimeout(() => NProgress.start(), 250)
})
router.on('progress', (event) => {
if (NProgress.isStarted() && event.detail.progress.percentage) {
NProgress.set((event.detail.progress.percentage / 100) * 0.9)
}
})
router.on('finish', (event) => {
clearTimeout(timeout)
if (!NProgress.isStarted()) {
return
}
if (event.detail.visit.completed) {
NProgress.done()
} else if (event.detail.visit.interrupted) {
NProgress.set(0)
} else if (event.detail.visit.cancelled) {
NProgress.done()
NProgress.remove()
}
})
```
--------------------------------
### Install React Dependencies
Source: https://inertia-rails.dev/guide/client-side-setup
Install the Inertia.js React adapter and Vite plugin using npm.
```bash
npm install @inertiajs/react @inertiajs/vite
```
--------------------------------
### Start Rails and Vite Development Servers
Source: https://inertia-rails.dev/guide/server-side-setup
Run the command to start both the Rails server and the Vite development server.
```bash
bin/dev
```
--------------------------------
### Svelte SSR Entry Point Example
Source: https://inertia-rails.dev/guide/server-side-rendering
A complete example of an SSR entry point for a Svelte application.
```js
import createServer from '@inertiajs/svelte/server'
createServer((page) =>
createInertiaApp({
page,
resolve: (name) => {
const pages = import.meta.glob('../pges/**/*.svelte')
return pages[`../pages/${name}.svelte`]()
},
setup({ App, props }) {
return render(App, { props })
},
}),
)
```
--------------------------------
### Install React Client-Side Adapter
Source: https://inertia-rails.dev/llms-full.txt
Install the React client-side adapter for Inertia.js v3.0 using npm.
```bash
npm install @inertiajs/react@^3.0
```
--------------------------------
### Install Inertia Dependencies
Source: https://inertia-rails.dev/guide/client-side-setup
Install the Inertia client-side adapter and Vite plugin using npm.
```bash
npm install @inertiajs/vue3 @inertiajs/vite
```
--------------------------------
### React Manual Setup
Source: https://inertia-rails.dev/guide/client-side-setup
Shows how to manually configure Inertia.js for React, including the `resolve` callback for component loading and the `setup` callback for rendering with `createRoot`.
```jsx
import { createInertiaApp } from '@inertiajs/react'
import { createRoot } from 'react-dom/client'
createInertiaApp({
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.jsx')
return pages[`../pages/${name}.jsx`]()
},
setup({ el, App, props }) {
createRoot(el).render()
},
})
```
--------------------------------
### Custom SSR Entry Point Example (Vue)
Source: https://inertia-rails.dev/guide/server-side-rendering
Example of a custom SSR entry point for Vue 3 applications, using `@inertiajs/vue3/server`.
```javascript
import createServer from '@inertiajs/vue3/server'
createServer((page) =>
createInertiaApp({
page,
render: renderToString,
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.vue')
return pages[`../pages/${name}.vue`]()
},
setup({ App, props, plugin }) {
return createSSRApp({
render: () => h(App, props),
}).use(plugin)
},
}),
)
```
--------------------------------
### Initialize shadcn/ui in Inertia Rails Project
Source: https://inertia-rails.dev/llms-full.txt
Run this command to initialize shadcn/ui in your project. It will guide you through style and theming choices, update configuration files, and install dependencies.
```bash
npx shadcn@latest init
✔ Preflight checks.
✔ Verifying framework. Found Vite.
✔ Validating Tailwind CSS.
✔ Validating import alias.
✔ Which style would you like to use? › New York
✔ Which color would you like to use as the base color? › Neutral
✔ Would you like to use CSS variables for theming? … no / yes
✔ Writing components.json.
✔ Checking registry.
✔ Updating tailwind.config.js
✔ Updating app/frontend/entrypoints/application.css
✔ Installing dependencies.
✔ Created 1 file:
- app/frontend/lib/utils.js
Success! Project initialization completed.
You may now add components.
```
--------------------------------
### Install NProgress Library
Source: https://inertia-rails.dev/guide/progress-indicators
Install the NProgress library using npm for custom page loading indicators.
```bash
npm install nprogress
```
--------------------------------
### Start NProgress on Inertia 'start' Event
Source: https://inertia-rails.dev/guide/progress-indicators
Use the 'start' event listener on the Inertia router to show the NProgress bar when a new Inertia visit begins.
```javascript
router.on('start', () => NProgress.start())
```
--------------------------------
### Generate Inertia Setup with Vite
Source: https://inertia-rails.dev/guide/server-side-setup
Use the Rails generator to automatically set up Inertia.js, detecting and installing Vite Rails if necessary.
```bash
bin/rails generate inertia:install
```
--------------------------------
### Partial Reload Request Example
Source: https://inertia-rails.dev/llms-full.txt
Demonstrates a GET request for a partial reload, specifying the 'events' prop to be included. This request targets the 'Events' component.
```http
REQUEST
GET: https://example.com/events
Accept: text/html, application/xhtml+xml
X-Requested-With: XMLHttpRequest
X-Inertia: true
X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5
X-Inertia-Partial-Data: events
X-Inertia-Partial-Component: Events
RESPONSE
HTTP/1.1 200 OK
Content-Type: application/json
{
"component": "Events",
"props": {
"auth": {...}, // NOT included
"categories": [...], // NOT included
"events": [...], // Included
"errors": {} // ALWAYS included
},
"url": "/events/80",
"version": "6b16b94d7c51cbe5b1fa42aac98241d5"
}
```
--------------------------------
### Install Svelte Client-Side Adapter
Source: https://inertia-rails.dev/llms-full.txt
Install the Svelte client-side adapter for Inertia.js v3.0 using npm.
```bash
npm install @inertiajs/svelte@^3.0
```
--------------------------------
### Install Svelte Dependencies
Source: https://inertia-rails.dev/guide/client-side-setup
Install the Inertia.js Svelte adapter and Vite plugin using npm.
```bash
npm install @inertiajs/svelte @inertiajs/vite
```
--------------------------------
### Install React Adapter for Inertia.js
Source: https://inertia-rails.dev/llms-full.txt
Use npm to install the React client-side adapter for Inertia.js v2.0.
```bash
npm
install
@inertiajs/
react
@^
2.0
```
--------------------------------
### Vue SSR Entry Point Example
Source: https://inertia-rails.dev/llms-full.txt
Example of a Vue SSR entry point file that runs in Node.js.
```js
import createServer from '@inertiajs/vue3/server'
createServer((page) =>
createInertiaApp({
page,
render: renderToString,
resolve: (name) => {
const pages = import.meta.glob('../pges/**/*.vue')
return pages[`../pages/${name}.vue`]()
},
setup({ App, props, plugin }) {
return createSSRApp({
render: () => h(App, props),
}).use(plugin)
},
}),
)
```
--------------------------------
### Basic Vue 3 Setup
Source: https://inertia-rails.dev/guide/client-side-setup
This is the basic setup for a Vue 3 application using Inertia.js. It configures component resolution and mounts the application.
```javascript
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
createInertiaApp({
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.vue')
return pages[`../pages/${name}.vue`]()
},
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el)
},
})
```
--------------------------------
### Install qs Dependency
Source: https://inertia-rails.dev/llms-full.txt
Install the 'qs' package directly if your application imports it, as it's no longer a dependency of @inertiajs/core.
```bash
npm install qs
```
--------------------------------
### Install Babel Plugin for Dynamic Imports
Source: https://inertia-rails.dev/guide/code-splitting
Install the necessary Babel plugin to enable dynamic imports. This is a prerequisite for code splitting.
```bash
npm install @babel/plugin-syntax-dynamic-import
```
--------------------------------
### Controller Generator Example Output
Source: https://inertia-rails.dev/guide/responses
This is an example output of the `inertia:controller` generator when creating a 'pages' controller with 'welcome' and 'next_steps' actions.
```bash
$ bin/rails generate inertia:controller pages welcome next_steps
create app/controllers/pages_controller.rb
route get 'pages/welcome'
get 'pages/next_steps'
invoke test_unit
create test/controllers/pages_controller_test.rb
invoke helper
create app/helpers/pages_helper.rb
invoke test_unit
invoke inertia_templates
create app/frontend/pages/pages
create app/frontend/pages/pages/welcome.jsx
create app/frontend/pages/pages/next_steps.jsx
```
--------------------------------
### Install Inertia Modal for React
Source: https://inertia-rails.dev/llms-full.txt
Install the Inertia Modal NPM package for React applications.
```bash
npm install @inertiaui/modal-react
```
--------------------------------
### Complete File Upload Form Example (Svelte)
Source: https://inertia-rails.dev/llms-full.txt
This example demonstrates a complete file upload form using Inertia's form helper in Svelte. It includes inputs for name and avatar, and shows how to display upload progress.
```svelte
```
--------------------------------
### Registering an Inertia Event Listener (Vue)
Source: https://inertia-rails.dev/guide/events
Use `router.on()` to register a listener for Inertia events like 'start'. This example shows how to log the URL when a visit begins.
```js
import { router } from '@inertiajs/vue3'
router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
--------------------------------
### Install Svelte Adapter for Inertia.js
Source: https://inertia-rails.dev/llms-full.txt
Use npm to install the Svelte client-side adapter for Inertia.js v2.0.
```bash
npm install @inertiajs/svelte@^2.0
```
--------------------------------
### Complete File Upload Form Example (React)
Source: https://inertia-rails.dev/llms-full.txt
This example demonstrates a complete file upload form using Inertia's form helper in React. It includes inputs for name and avatar, and shows how to display upload progress.
```jsx
import { useForm } from '@inertiajs/react'
const { data, setData, post, progress } = useForm({
name: null,
avatar: null,
})
function submit(e) {
e.preventDefault()
post('/users')
}
return (
)
```
--------------------------------
### Start SSR Server Manually
Source: https://inertia-rails.dev/guide/server-side-rendering
Use this command to start the SSR server if you are not using Puma or prefer manual management.
```bash
bin/vite ssr
```
--------------------------------
### Install Vue 3 Client-Side Adapter
Source: https://inertia-rails.dev/llms-full.txt
Install the Vue 3 client-side adapter for Inertia.js v3.0 using npm.
```bash
npm install @inertiajs/vue3@^3.0
```
--------------------------------
### Install Inertia Modal for Vue
Source: https://inertia-rails.dev/llms-full.txt
Install the Inertia Modal NPM package for Vue applications.
```bash
npm install @inertiaui/modal-vue
```
--------------------------------
### Scaffold Generator Example Output
Source: https://inertia-rails.dev/guide/responses
This is an example output of the `inertia:scaffold` generator when creating a 'Post' resource with 'title' and 'body' fields.
```bash
$ bin/rails generate inertia:scaffold Post title:string body:text
invoke active_record
create db/migrate/20240611123952_create_posts.rb
create app/models/post.rb
invoke test_unit
create test/models/post_test.rb
create test/fixtures/posts.yml
invoke resource_route
route resources :posts
invoke scaffold_controller
create app/controllers/posts_controller.rb
invoke inertia_templates
create app/frontend/pages/posts
create app/frontend/pages/posts/index.svelte
create app/frontend/pages/posts/edit.svelte
create app/frontend/pages/posts/show.svelte
create app/frontend/pages/posts/new.svelte
create app/frontend/pages/posts/form.svelte
create app/frontend/pages/posts/post.svelte
invoke resource_route
invoke test_unit
create test/controllers/posts_controller_test.rb
create test/system/posts_test.rb
invoke helper
create app/helpers/posts_helper.rb
invoke test_unit
```
--------------------------------
### Install React with Vite Plugin
Source: https://inertia-rails.dev/guide/client-side-setup
Install React, ReactDOM, and its corresponding Vite plugin using npm. This is required for React applications using Inertia.js.
```bash
npm install react react-dom @vitejs/plugin-react
```
--------------------------------
### Install Vite Plugin for SSR
Source: https://inertia-rails.dev/guide/server-side-rendering
Install the @inertiajs/vite plugin to automatically handle SSR configuration, including development mode.
```bash
npm install @inertiajs/vite
```
--------------------------------
### Install Vue 3 Adapter for Inertia.js
Source: https://inertia-rails.dev/llms-full.txt
Use npm to install the Vue 3 client-side adapter for Inertia.js v2.0.
```bash
npm install @inertiajs/vue3@^2.0
```
--------------------------------
### Basic Infinite Scroll Setup (Vue)
Source: https://inertia-rails.dev/guide/infinite-scroll
This snippet shows the basic setup for the InfiniteScroll component in Vue. It requires importing the component and specifying the prop containing paginated data.
```vue
{{ user.name }}
```
--------------------------------
### Install Vue and Vite Plugin
Source: https://inertia-rails.dev/guide/client-side-setup
Installs the Vue package and its corresponding Vite plugin using npm. This is a prerequisite for using Vue with Inertia.js.
```bash
npm install vue @vitejs/plugin-vue
```
--------------------------------
### Install Svelte with Vite Plugin
Source: https://inertia-rails.dev/guide/client-side-setup
Install Svelte and its corresponding Vite plugin using npm. This is necessary for Svelte applications integrating with Inertia.js.
```bash
npm install svelte @sveltejs/vite-plugin-svelte
```
--------------------------------
### Install Inertia Rails
Source: https://inertia-rails.dev/
Rails generator command to install Inertia.js, configuring Vite, the chosen framework, and creating example pages.
```shell
bin/rails g inertia:install
```
--------------------------------
### Start Loading Indicator with Delay
Source: https://inertia-rails.dev/guide/progress-indicators
In the 'start' event listener, initiate a timeout to display the progress bar after 250 milliseconds. This prevents the indicator from appearing on very quick page visits.
```javascript
router.on('start', () => {
timeout = setTimeout(() => NProgress.start(), 250)
})
```
--------------------------------
### Rails Controller Example
Source: https://inertia-rails.dev/
Example of a Rails controller action rendering Inertia with user data. This snippet demonstrates how to pass an array of user objects, each with specific attributes, to the frontend.
```ruby
class UsersController < ApplicationController
def index
render inertia: {
users: User.active.map do |user|
user.as_json(only: [:id, :name, :email])
end
}
end
end
```
--------------------------------
### Page Response with Shared Props
Source: https://inertia-rails.dev/guide/instant-visits
Example of a page response including props, component name, and a list of shared prop keys.
```json
{
"component": "Dashboard",
"props": {
"auth": { "user": "..." },
"stats": {
/*...*/
}
},
"sharedProps": ["auth"]
}
```
--------------------------------
### Create Manual SSR Entry Point File
Source: https://inertia-rails.dev/guide/server-side-rendering
Create an SSR entry point file (e.g., app/frontend/ssr/ssr.js) for manual SSR configuration.
```bash
touch app/frontend/ssr/ssr.js
```
--------------------------------
### Load Data Before Element is Visible (Svelte)
Source: https://inertia-rails.dev/llms-full.txt
Use the `buffer` prop to specify the number of pixels before the element is visible to start loading data. This example shows the Svelte implementation.
```svelte
{#snippet fallback()}
Loading...
{/snippet}
{#each permissions as permission}
{/each}
```
--------------------------------
### Load Data Before Element is Visible (React)
Source: https://inertia-rails.dev/llms-full.txt
Use the `buffer` prop to specify the number of pixels before the element is visible to start loading data. This example shows the React implementation.
```jsx
import { WhenVisible } from '@inertiajs/react'
export default () => (
Loading...
}
>
)
```
--------------------------------
### Vue Error Page Component Example
Source: https://inertia-rails.dev/guide/error-handling
A basic Vue component to display error messages based on the HTTP status code. This component can be used as a starting point for your custom Inertia error pages.
```vue
{{ title }}
{{ description }}
```
--------------------------------
### Registering an Inertia Event Listener using Native Browser Events (Vue)
Source: https://inertia-rails.dev/guide/events
Inertia events can also be listened to using standard `document.addEventListener` by prepending 'inertia:' to the event name. This example logs the URL when a visit starts.
```js
import { router } from '@inertiajs/vue3'
document.addEventListener('inertia:start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
--------------------------------
### Initialize Inertia App (Minimal)
Source: https://inertia-rails.dev/guide/client-side-setup
Update your main JavaScript file to boot your Inertia app. The Vite plugin handles page resolution and mounting automatically.
```js
import { createInertiaApp } from '@inertiajs/vue3'
createInertiaApp()
```
--------------------------------
### Create SSR Entry Point (React)
Source: https://inertia-rails.dev/guide/server-side-rendering
Creates the SSR entry point file for React applications.
```bash
touch app/frontend/ssr/ssr.jsx
```
--------------------------------
### Creating a User with Flash Notice
Source: https://inertia-rails.dev/guide/flash-data
This example shows how to create a user and redirect with a flash notice using Inertia Rails. It demonstrates the integration with Rails' standard flash mechanism.
```ruby
class UsersController < ApplicationController
def create
user = User.new(user_params)
if user.save
redirect_to users_url, notice: 'User created successfully!'
else
redirect_to new_user_url, inertia: { errors: user.errors }
end
end
end
```
--------------------------------
### React Global View Transition Configuration
Source: https://inertia-rails.dev/llms-full.txt
Set up `visitOptions` within `createInertiaApp` in React to globally activate view transitions for all navigation.
```js
import { createInertiaApp } from '@inertiajs/react'
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return { viewTransition: true }
},
},
})
```
--------------------------------
### Global View Transition Configuration
Source: https://inertia-rails.dev/guide/view-transitions
Enable view transitions for all visits by configuring the 'visitOptions' callback during Inertia app initialization.
```javascript
import { createInertiaApp } from '@inertiajs/vue3'
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return { viewTransition: true }
},
},
})
```
--------------------------------
### Initialize Inertia App (React)
Source: https://inertia-rails.dev/guide/client-side-setup
Update your main JavaScript file to boot your Inertia app using the React adapter. The Vite plugin handles page resolution and mounting automatically.
```javascript
import { createInertiaApp } from '@inertiajs/react'
createInertiaApp()
```
--------------------------------
### Initialize Inertia App (Svelte)
Source: https://inertia-rails.dev/guide/client-side-setup
Update your main JavaScript file to boot your Inertia app using the Svelte adapter. The Vite plugin handles page resolution and mounting automatically.
```javascript
import { createInertiaApp } from '@inertiajs/svelte'
createInertiaApp()
```
--------------------------------
### Install lodash-es Dependency
Source: https://inertia-rails.dev/llms-full.txt
Install the 'lodash-es' package directly if your application imports it, as it's no longer a dependency of @inertiajs/core.
```bash
npm install lodash-es
```
--------------------------------
### Implementing Optimistic Updates
Source: https://inertia-rails.dev/guide/http-requests
Shows how to use the `optimistic()` method to apply immediate UI updates before the server response. If the request fails, the changes are automatically rolled back.
```javascript
http
.optimistic((data) => ({
likes: data.likes + 1,
}))
.post('/api/likes')
```
--------------------------------
### Svelte: Basic Instant Visit Link
Source: https://inertia-rails.dev/llms-full.txt
For Svelte, use the `Link` component with the `component` prop to enable instant visits. The target component renders immediately.
```svelte
Dashboard
Dashboard
```
--------------------------------
### Install inertia_rails-contrib Gem
Source: https://inertia-rails.dev/llms-full.txt
Install the inertia_rails-contrib gem to your Rails application to enable base URL support for modals. This enhances accessibility and SEO.
```bash
bundle add inertia_rails-contrib
```
--------------------------------
### Visit with View Transition Callback
Source: https://inertia-rails.dev/guide/view-transitions
Initiate a visit to another page and provide a callback to access the ViewTransition instance for logging transition events.
```javascript
import { router } from '@inertiajs/vue3'
router.visit('/another-page', {
viewTransition: (transition) => {
transition.ready.then(() => console.log('Transition ready'))
transition.updateCallbackDone.then(() => console.log('DOM updated'))
transition.finished.then(() => console.log('Transition finished'))
},
})
```
--------------------------------
### Using Standard Rails Flash Patterns
Source: https://inertia-rails.dev/guide/flash-data
Demonstrates how to set standard Rails flash messages for 'notice' and 'alert' which are automatically exposed to the frontend by Inertia.
```ruby
flash[:notice] = 'Success!'
flash[:alert] = 'Something went wrong'
redirect_to users_url
```
--------------------------------
### Remove Inertia 'start' Event Listener (Svelte)
Source: https://inertia-rails.dev/llms-full.txt
Register a listener for the 'start' event and store the callback to remove it later. This is useful for manual cleanup.
```js
import { router } from '@inertiajs/svelte'
let removeStartEventListener = router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
// Remove the listener...
removeStartEventListener()
```
--------------------------------
### Import NProgress and Inertia Router (Svelte)
Source: https://inertia-rails.dev/llms-full.txt
Import NProgress and the Inertia router for Svelte applications.
```javascript
import NProgress from 'nprogress'
import { router } from '@inertiajs/svelte'
```
--------------------------------
### router.visit() Method Options
Source: https://inertia-rails.dev/guide/manual-visits
Use the `router.visit()` method to make programmatic Inertia visits. It accepts a URL and an options object to customize the visit behavior.
```javascript
import { router } from '@inertiajs/vue3'
router.visit(url, {
method: 'get',
data: {},
replace: false,
preserveState: false,
preserveScroll: false,
only: [],
except: [],
headers: {},
errorBag: null,
forceFormData: false,
queryStringArrayFormat: 'brackets',
async: false,
showProgress: true,
fresh: false,
reset: [],
preserveUrl: false,
prefetch: false,
preserveErrors: false,
viewTransition: false,
component: null,
pageProps: null,
onCancelToken: (cancelToken) => {},
onCancel: () => {},
onBefore: (visit) => {},
onStart: (visit) => {},
onProgress: (progress) => {},
onSuccess: (page) => {},
onError: (errors) => {},
onHttpException: (response) => {},
onNetworkError: (error) => {},
onFinish: (visit) => {},
onPrefetching: () => {},
onPrefetched: () => {},
})
```
--------------------------------
### Remove Inertia 'start' Event Listener (React)
Source: https://inertia-rails.dev/llms-full.txt
Register a listener for the 'start' event and store the callback to remove it later. This is useful for manual cleanup.
```jsx
import { router } from '@inertiajs/react'
let removeStartEventListener = router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
// Remove the listener...
removeStartEventListener()
```
--------------------------------
### Registering Inertia Event Listener (React)
Source: https://inertia-rails.dev/llms-full.txt
Register a listener for the 'start' event using `router.on()` in React. This allows you to execute code when a navigation starts.
```javascript
import { router } from '@inertiajs/react'
router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
```
--------------------------------
### React: Basic Instant Visit Link
Source: https://inertia-rails.dev/llms-full.txt
In React, use the `Link` component with the `component` prop for instant visits. The specified component will be rendered right away.
```jsx
import { Link } from '@inertiajs/react'
export default () => (
Dashboard
)
```
--------------------------------
### Creating Independent useHttp Instances
Source: https://inertia-rails.dev/guide/http-requests
Demonstrates creating separate `useHttp` instances to manage independent reactive states, preventing state collisions between different requests.
```javascript
const search = useHttp({ query: '' })
const upload = useHttp({ file: null })
```
--------------------------------
### Listen for Inertia.js 'start' event in Vue
Source: https://inertia-rails.dev/guide/events
Register a listener for the 'start' event to log the URL of the visit. This listener is automatically removed when the component unmounts.
```vue
```
--------------------------------
### Manual Polling Control with autoStart: false (Svelte)
Source: https://inertia-rails.dev/llms-full.txt
Configure the usePoll helper with autoStart: false to manually control polling. Use the returned start and stop methods to manage polling lifecycle.
```svelte
```
--------------------------------
### Auto-remove Inertia 'start' Listener on Unmount (Svelte)
Source: https://inertia-rails.dev/llms-full.txt
Automatically remove the 'start' event listener when a Svelte component unmounts using `$effect`. Ensures no memory leaks.
```js
import { router } from '@inertiajs/svelte'
$effect(() => {
return router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
})
```
--------------------------------
### Auto-remove Inertia 'start' Listener on Unmount (React)
Source: https://inertia-rails.dev/llms-full.txt
Automatically remove the 'start' event listener when a React component unmounts using `useEffect`. Ensures no memory leaks.
```jsx
import { useEffect } from 'react'
import { router } from '@inertiajs/react'
useEffect(() => {
return router.on('start', (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
})
}, [])
```
--------------------------------
### Configuring Global Visit Options
Source: https://inertia-rails.dev/guide/manual-visits
Set a 'visitOptions' callback during Inertia app initialization to modify visit options globally.
```javascript
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
createInertiaApp({
// ...
defaults: {
visitOptions: (href, options) => {
return {
headers: {
...options.headers,
'X-Custom-Header': 'value',
},
}
},
},
})
```
--------------------------------
### Svelte: Inline Optimistic Update
Source: https://inertia-rails.dev/llms-full.txt
Demonstrates how to pass an optimistic callback directly in visit options for Svelte.
```javascript
import { router } from '@inertiajs/svelte'
router.post(
`/posts/${post.id}/like`,
{},
{
optimistic: (props) => ({
post: { ...props.post, likes: props.post.likes + 1 },
}),
},
)
```
--------------------------------
### Manually Control Polling with usePoll
Source: https://inertia-rails.dev/guide/polling
Use `autoStart: false` to prevent automatic polling on mount. Then, use the returned `start` and `stop` functions to control polling manually.
```vue
```
--------------------------------
### Conditional Progress Bar Start in Finish Event
Source: https://inertia-rails.dev/guide/progress-indicators
Check if the progress bar has already started before proceeding in the 'finish' event. This prevents showing the bar prematurely if the timeout hasn't completed.
```javascript
router.on('finish', (event) => {
clearTimeout(timeout)
if (!NProgress.isStarted()) {
return
}
// ...
})
```
--------------------------------
### Basic useHttp Usage in Vue
Source: https://inertia-rails.dev/guide/http-requests
Demonstrates how to use the `useHttp` hook to fetch data on input change. The request does not trigger page navigation.
```vue
Searching...
```
--------------------------------
### Remove Native 'inertia:start' Event Listener (Svelte)
Source: https://inertia-rails.dev/llms-full.txt
Add a listener for the native 'inertia:start' browser event and then remove it using `document.removeEventListener`. Useful for custom browser event handling.
```js
import { router } from '@inertiajs/svelte'
let startEventListener = (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
}
document.addEventListener('inertia:start', startEventListener)
// Remove the listener...
document.removeEventListener('inertia:start', startEventListener)
```
--------------------------------
### Remove Native 'inertia:start' Event Listener (React)
Source: https://inertia-rails.dev/llms-full.txt
Add a listener for the native 'inertia:start' browser event and then remove it using `document.removeEventListener`. Useful for custom browser event handling.
```jsx
import { router } from '@inertiajs/react'
let startEventListener = (event) => {
console.log(`Starting a visit to ${event.detail.visit.url}`)
}
document.addEventListener('inertia:start', startEventListener)
// Remove the listener...
document.removeEventListener('inertia:start', startEventListener)
```