### React SSR Setup Source: https://inertia-rails.dev/guide/server-side-rendering Example of setting up server-side rendering for a React application using Inertia. ```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('../pages/**/*.jsx') return pages[`../pages/${name}.jsx`]() }, setup: ({ App, props }) => , }), ) ``` -------------------------------- ### Vue Manual Setup Source: https://inertia-rails.dev/guide/client-side-setup Configure Inertia.js for Vue by providing custom resolve and setup callbacks. This example shows how to lazy-load Vue components from the '../pages' directory. ```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) }, }) ``` -------------------------------- ### Svelte SSR Setup Source: https://inertia-rails.dev/guide/server-side-rendering Example of setting up server-side rendering for a Svelte application using Inertia. ```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 }) }, }), ) ``` -------------------------------- ### Vue SSR Setup Source: https://inertia-rails.dev/guide/server-side-rendering Example of setting up server-side rendering for a Vue.js application using Inertia. ```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) }, }), ) ``` -------------------------------- ### Handling Request Start with 'start' Event (Svelte) Source: https://inertia-rails.dev/guide/events Use the 'start' event to log when a request to the server begins. This event is useful for triggering loading indicators. ```js import { router } from '@inertiajs/svelte' router.on('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) ``` -------------------------------- ### Start Progress Bar on Visit Start Source: https://inertia-rails.dev/guide/progress-indicators Use the 'start' event listener to initiate NProgress when an Inertia visit begins. ```javascript router.on('start', () => NProgress.start()) ``` -------------------------------- ### Svelte Manual Setup Source: https://inertia-rails.dev/guide/client-side-setup Manually configure Inertia.js for Svelte using custom resolve and setup callbacks. This example illustrates lazy-loading Svelte components from the '../pages' directory. ```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 }) }, }) ``` -------------------------------- ### React SSR Entry Point Example Source: https://inertia-rails.dev/guide/server-side-rendering An example of a React SSR entry point file that runs in Node.js. ```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 }) => , }), ) ``` -------------------------------- ### Handling Request Start with 'start' Event (React) Source: https://inertia-rails.dev/guide/events Use the 'start' event to log when a request to the server begins. This event is useful for triggering loading indicators. ```jsx import { router } from '@inertiajs/react' router.on('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) ``` -------------------------------- ### Production Build and Server Start Source: https://inertia-rails.dev/guide/server-side-rendering Commands to build both browser and SSR bundles for production and start the Node.js SSR server. ```bash npm run build node public/assets-ssr/inertia.js ``` -------------------------------- ### Register a One-time 'start' Event Listener (Svelte) Source: https://inertia-rails.dev/guide/events Register a listener that fires only once when a visit starts. The listener is automatically removed after its first invocation. This example is for Svelte. ```js import { router } from '@inertiajs/svelte' router.once('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) ``` -------------------------------- ### Install NProgress Library Source: https://inertia-rails.dev/guide/progress-indicators Install the NProgress library using npm to manage the progress bar. ```bash npm install nprogress ``` -------------------------------- ### Scaffold Generator Example Output Source: https://inertia-rails.dev/guide/responses Example output from running the inertia:scaffold generator for a 'Post' resource. ```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 Client-Side Adapter Source: https://inertia-rails.dev/guide/upgrade-guide Install the React client-side adapter for Inertia.js v3.0 using npm. ```bash npm install @inertiajs/react@^3.0 ``` -------------------------------- ### Handling Request Start with 'start' Event (Vue) Source: https://inertia-rails.dev/guide/events Use the 'start' event to log when a request to the server begins. This event is useful for triggering loading indicators. ```js import { router } from '@inertiajs/vue3' router.on('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) ``` -------------------------------- ### Basic Form Setup with useForm (Svelte) Source: https://inertia-rails.dev/guide/forms Initializes a form with state, error handling, and submission logic using `useForm` in Svelte. ```svelte
{#if form.errors.email}
{form.errors.email}
{/if} {#if form.errors.password}
{form.errors.password}
{/if} Remember Me
``` -------------------------------- ### Start Rails and Vite Development Servers Source: https://inertia-rails.dev/guide/server-side-setup Command to start both the Rails server and the Vite development server simultaneously. ```bash bin/dev ``` -------------------------------- ### Basic Form Setup with useForm (React) Source: https://inertia-rails.dev/guide/forms Initializes a form with state, error handling, and submission logic using `useForm` in React. ```jsx import { useForm } from '@inertiajs/react' const { data, setData, post, processing, errors } = useForm({ email: '', password: '', remember: false, }) function submit(e) { e.preventDefault() post('/login') } return (
setData('email', e.target.value)} /> {errors.email &&
{errors.email}
} setData('password', e.target.value)} /> {errors.password &&
{errors.password}
} setData('remember', e.target.checked)} /> Remember Me
) ``` -------------------------------- ### Basic Form Setup with useForm (Vue) Source: https://inertia-rails.dev/guide/forms Initializes a form with state, error handling, and submission logic using `useForm` in Vue. ```vue ``` -------------------------------- ### Install Svelte Client-Side Adapter Source: https://inertia-rails.dev/guide/upgrade-guide Install the Svelte client-side adapter for Inertia.js v3.0 using npm. ```bash npm install @inertiajs/svelte@^3.0 ``` -------------------------------- ### Svelte SSR Entry Point Example Source: https://inertia-rails.dev/guide/server-side-rendering An example of a Svelte SSR entry point file that runs in Node.js. ```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 Vite Plugin Source: https://inertia-rails.dev/guide/server-side-rendering Install the Inertia.js Vite plugin using npm. ```bash npm install @inertiajs/vite ``` -------------------------------- ### Install React Adapter for Inertia.js v2.0 Source: https://inertia-rails.dev/guide/upgrade-guide Install the React client-side adapter for Inertia.js v2.0 using npm. ```bash npm install @inertiajs/react@^2.0 ``` -------------------------------- ### Initialize shadcn/ui Source: https://inertia-rails.dev/cookbook/integrating-shadcn-ui Run this command to initialize shadcn/ui in your project. It will guide you through configuration options like style, color, and theming. ```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. ``` -------------------------------- ### React Manual Setup Source: https://inertia-rails.dev/guide/client-side-setup Set up Inertia.js for React with manual resolve and setup callbacks. This snippet demonstrates lazy-loading React components from the '../pages' directory. ```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() }, }) ``` -------------------------------- ### Controller Generator Example Output Source: https://inertia-rails.dev/guide/responses Example output from running the inertia:controller generator for 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 ``` -------------------------------- ### Vue SSR Entry Point Example Source: https://inertia-rails.dev/guide/server-side-rendering An 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) }, }), ) ``` -------------------------------- ### Register a One-time 'start' Event Listener (React) Source: https://inertia-rails.dev/guide/events Register a listener that fires only once when a visit starts. The listener is automatically removed after its first invocation. This example is for React. ```jsx import { router } from '@inertiajs/react' router.once('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) ``` -------------------------------- ### Partial Reload Request and Response Example Source: https://inertia-rails.dev/guide/the-protocol Demonstrates a GET request with headers for a partial reload, specifying 'events' as the data to include. The response shows only the requested 'events' prop, along with always-included 'auth' and 'errors' props. ```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" } ``` -------------------------------- ### Vue: Load Data with Buffer Source: https://inertia-rails.dev/guide/load-when-visible Use the 'buffer' prop to start loading data a specified number of pixels before the element is visible. This example shows how to load 'permissions' data. ```vue ``` -------------------------------- ### Install qs Dependency Source: https://inertia-rails.dev/guide/upgrade-guide Install the 'qs' package directly if your application imports it, as it's no longer a direct dependency of @inertiajs/core. ```bash npm install qs ``` -------------------------------- ### Install Svelte Adapter for Inertia.js v2.0 Source: https://inertia-rails.dev/guide/upgrade-guide Install the Svelte client-side adapter for Inertia.js v2.0 using npm. ```bash npm install @inertiajs/svelte@^2.0 ``` -------------------------------- ### Install React and 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 integration with Inertia. ```bash npm install react react-dom @vitejs/plugin-react ``` -------------------------------- ### Install Inertia Modal for React Source: https://inertia-rails.dev/cookbook/inertia-modal Install the Inertia Modal NPM package for React applications. ```bash npm install @inertiaui/modal-react ``` -------------------------------- ### Install Babel Plugin for Dynamic Imports Source: https://inertia-rails.dev/guide/code-splitting Install the `@babel/plugin-syntax-dynamic-import` package to enable dynamic imports for code splitting with Webpack/Shakapacker. ```bash npm install @babel/plugin-syntax-dynamic-import ``` -------------------------------- ### Install Vue and Vite Plugin Source: https://inertia-rails.dev/guide/client-side-setup Install Vue and its corresponding Vite plugin using npm. This is a prerequisite for using Vue with Inertia. ```bash npm install vue @vitejs/plugin-vue ``` -------------------------------- ### Install Inertia.js Vite Plugin Source: https://inertia-rails.dev/guide/upgrade-guide Install the optional Inertia.js Vite plugin for simplified SSR and component resolution shorthand. ```bash npm install @inertiajs/vite@^3.0 ``` -------------------------------- ### Install Vue 3 Client-Side Adapter Source: https://inertia-rails.dev/guide/upgrade-guide Install the Vue 3 client-side adapter for Inertia.js v3.0 using npm. ```bash npm install @inertiajs/vue3@^3.0 ``` -------------------------------- ### Generate Inertia Setup with Rails Source: https://inertia-rails.dev/guide/server-side-setup Use the Rails generator to automatically install and configure Inertia.js, including Vite, frontend frameworks, and Tailwind CSS. ```bash bin/rails generate inertia:install ``` -------------------------------- ### Install Svelte and Vite Plugin Source: https://inertia-rails.dev/guide/client-side-setup Install Svelte and its corresponding Vite plugin using npm. This step is necessary for using Svelte with Inertia. ```bash npm install svelte @sveltejs/vite-plugin-svelte ``` -------------------------------- ### Install Inertia Modal for Vue Source: https://inertia-rails.dev/cookbook/inertia-modal Install the Inertia Modal NPM package for Vue applications. ```bash npm install @inertiaui/modal-vue ``` -------------------------------- ### Install Vue 3 Adapter for Inertia.js v2.0 Source: https://inertia-rails.dev/guide/upgrade-guide Install the Vue 3 client-side adapter for Inertia.js v2.0 using npm. ```bash npm install @inertiajs/vue3@^2.0 ``` -------------------------------- ### Install Inertia Vue3, React, and Svelte Adapters with Vite Source: https://inertia-rails.dev/guide/client-side-setup Install the Inertia client-side adapter for your chosen framework (Vue, React, or Svelte) along with the Vite plugin. This command should be run in your project's root directory. ```bash npm install @inertiajs/vue3 @inertiajs/vite ``` ```bash npm install @inertiajs/react @inertiajs/vite ``` ```bash npm install @inertiajs/svelte @inertiajs/vite ``` -------------------------------- ### Start Progress Bar with Delay Source: https://inertia-rails.dev/guide/progress-indicators Modify the 'start' event listener to use `setTimeout` to delay the initiation of NProgress by 250 milliseconds. ```javascript router.on('start', () => { timeout = setTimeout(() => NProgress.start(), 250) }) ``` -------------------------------- ### Manually Start SSR Server Source: https://inertia-rails.dev/guide/server-side-rendering Start the Inertia.js SSR server manually using the Vite command. This is an alternative to using the Puma plugin for managing the SSR process. ```bash bin/vite ssr ``` -------------------------------- ### String Cache Key Example Source: https://inertia-rails.dev/guide/cached-props Utilize a simple string as a cache key for static data that doesn't depend on dynamic factors. ```ruby InertiaRails.cache('sidebar_nav') { NavigationItem.tree } ``` -------------------------------- ### Register a One-time 'start' Event Listener (Vue) Source: https://inertia-rails.dev/guide/events Register a listener that fires only once when a visit starts. The listener is automatically removed after its first invocation. This example is for Vue. ```js import { router } from '@inertiajs/vue3' router.once('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) ``` -------------------------------- ### Controller Action Validation (Good Example) Source: https://inertia-rails.dev/guide/precognition Shows the correct way to use precognition with a form object to validate multiple models in a single call. ```ruby def create form = RegistrationForm.new(params) precognition!(form) # Validates user + profile together end ``` -------------------------------- ### Svelte: Prefetch on Mousedown Source: https://inertia-rails.dev/guide/prefetching Start prefetching data on mousedown instead of hover by setting prefetch to 'click'. ```svelte Users ``` -------------------------------- ### React Client-Side Hydration Setup Source: https://inertia-rails.dev/guide/server-side-rendering Update your `inertia.js` file to use `hydrateRoot` for React applications to enable server-side rendering. ```javascript import { createRoot } from 'react-dom/client' // [!code --] import { hydrateRoot } from 'react-dom/client' // [!code ++] createInertiaApp({ resolve: (name) => { const pages = import.meta.glob('../pages/**/*.jsx') return pages[`../pages/${name}.jsx`]() }, setup({ el, App, props }) { createRoot(el).render() // [!code --] hydrateRoot(el, ) // [!code ++] }, }) ``` -------------------------------- ### Remove a One-time 'start' Event Listener (Svelte) Source: https://inertia-rails.dev/guide/events Register a one-time listener and obtain a callback to remove it before it fires. This example is for Svelte. ```js import { router } from '@inertiajs/svelte' let removeStartEventListener = router.once('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) // Remove the listener before it fires... removeStartEventListener() ``` -------------------------------- ### Add Inertia.js Core as a Direct Dependency Source: https://inertia-rails.dev/guide/typescript Alternatively, install @inertiajs/core directly into your project to avoid module resolution problems. ```bash pnpm add @inertiajs/core ``` -------------------------------- ### Controller Redirects in Rails Source: https://inertia-rails.dev/guide/redirects Example of handling user creation and redirecting in a Rails controller. It shows both successful creation redirects and redirects with error data. ```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 ``` -------------------------------- ### Remove a One-time 'start' Event Listener (React) Source: https://inertia-rails.dev/guide/events Register a one-time listener and obtain a callback to remove it before it fires. This example is for React. ```jsx import { router } from '@inertiajs/react' let removeStartEventListener = router.once('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) // Remove the listener before it fires... removeStartEventListener() ``` -------------------------------- ### Vue Client-Side Hydration Setup Source: https://inertia-rails.dev/guide/server-side-rendering Update your `inertia.js` file to use `createSSRApp` and `hydrate` for Vue applications to enable server-side rendering. ```javascript import { createApp, h } from 'vue' // [!code --] import { createSSRApp, h } from 'vue' // [!code ++] 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) }) // [!code --] createSSRApp({ render: () => h(App, props) }) // [!code ++] .use(plugin) .mount(el) }, }) ``` -------------------------------- ### Controller Handling Form Object Source: https://inertia-rails.dev/guide/precognition Example of a controller action that instantiates and saves a `RegistrationForm`, handling success and error redirection. ```ruby class RegistrationsController < ApplicationController def create form = RegistrationForm.new(params) if form.save redirect_to form.user else redirect_back_or_to new_registration_path, inertia: { errors: form.errors } end end end ``` -------------------------------- ### Remove a One-time 'start' Event Listener (Vue) Source: https://inertia-rails.dev/guide/events Register a one-time listener and obtain a callback to remove it before it fires. This example is for Vue. ```js import { router } from '@inertiajs/vue3' let removeStartEventListener = router.once('start', (event) => { console.log(`Starting a visit to ${event.detail.visit.url}`) }) // Remove the listener before it fires... removeStartEventListener() ``` -------------------------------- ### Svelte: Load Data with Buffer Source: https://inertia-rails.dev/guide/load-when-visible Svelte's implementation of WhenVisible also uses the 'buffer' prop for pre-loading. This example loads 'permissions' data with a 500px buffer. ```svelte {#snippet fallback()}
Loading...
{/snippet} {#each permissions as permission} {/each}
``` -------------------------------- ### Rails Controller to Render Inertia Page Source: https://inertia-rails.dev/guide/pages Example of a Rails controller action that fetches a user and renders an Inertia page with the user data as a prop. ```ruby class UsersController < ApplicationController def show user = User.find(params[:id]) render inertia: { user: user } end end ``` -------------------------------- ### Vue 3.3+ Persistent Layout with defineOptions Source: https://inertia-rails.dev/guide/layouts Alternatively, Vue 3.3+ users can define a persistent layout within ``` -------------------------------- ### Array Cache Key Example Source: https://inertia-rails.dev/guide/cached-props Create a composite cache key by passing an array of values. This is useful for keys that depend on multiple dynamic factors. ```ruby InertiaRails.cache(['stats', current_user.id]) { Stats.for(current_user) } ``` -------------------------------- ### Inertia Request and Response Example Source: https://inertia-rails.dev/guide/the-protocol Demonstrates a typical Inertia request with the 'X-Inertia: true' header and the corresponding JSON response payload containing component, props, URL, and version. ```http REQUEST GET: https://example.com/events/80 Accept: text/html, application/xhtml+xml X-Requested-With: XMLHttpRequest X-Inertia: true X-Inertia-Version: 6b16b94d7c51cbe5b1fa42aac98241d5 RESPONSE HTTP/1.1 200 OK Content-Type: application/json Vary: X-Inertia X-Inertia: true { "component": "Event", "props": { "errors": {}, "event": { "id": 80, "title": "Birthday party", "start_date": "2019-06-02", "description": "Come out and celebrate Jonathan's 36th birthday party!" } }, "url": "/events/80", "version": "6b16b94d7c51cbe5b1fa42aac98241d5", "encryptHistory": true } ``` -------------------------------- ### 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 ``` -------------------------------- ### Create SSR Entry Point (Vue) Source: https://inertia-rails.dev/guide/server-side-rendering Creates the SSR entry point file for Vue applications. ```bash touch app/frontend/ssr/ssr.js ``` -------------------------------- ### Install inertia_rails-contrib Gem Source: https://inertia-rails.dev/cookbook/inertia-modal Install the inertia_rails-contrib gem to your Rails application to enable base URL support for modals. ```bash bundle add inertia_rails-contrib ``` -------------------------------- ### 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() ``` -------------------------------- ### Configure Global Visit Options with Custom Headers (Svelte) Source: https://inertia-rails.dev/guide/manual-visits Configure a `visitOptions` callback during app initialization to globally modify visit options for all requests. This example adds a custom header. ```javascript import { createInertiaApp } from '@inertiajs/svelte' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { headers: { ...options.headers, 'X-Custom-Header': 'value', }, } }, }, }) ``` -------------------------------- ### Install lodash-es Dependency Source: https://inertia-rails.dev/guide/upgrade-guide Install the 'lodash-es' package directly if your application imports it, as it's no longer a direct dependency of @inertiajs/core. ```bash npm install lodash-es ``` -------------------------------- ### 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() ``` -------------------------------- ### Basic Instant Visit with React Link Source: https://inertia-rails.dev/guide/instant-visits Use the `component` prop on the `Link` component in React to enable instant visits. This immediately renders the specified component while the server request is made in the background. ```jsx import { Link } from '@inertiajs/react' export default () => ( Dashboard ) ``` -------------------------------- ### Standard Rails Flash with Inertia Source: https://inertia-rails.dev/guide/flash-data Demonstrates how to use standard Rails flash keys like 'notice' within a controller action that redirects. Inertia automatically includes these by default. ```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 ``` -------------------------------- ### Basic Instant Visit with Svelte Link Source: https://inertia-rails.dev/guide/instant-visits Use the `component` prop on the `Link` component in Svelte to enable instant visits. This immediately renders the specified component while the server request is made in the background. ```svelte Dashboard Dashboard ``` -------------------------------- ### Basic Instant Visit with Vue Link Source: https://inertia-rails.dev/guide/instant-visits Use the `component` prop on the `Link` component to enable instant visits. This immediately renders the specified component while the server request is made in the background. ```vue ``` -------------------------------- ### Preserve State with get Method (Svelte) Source: https://inertia-rails.dev/guide/manual-visits Use this when you need to preserve the component's state when using the `get` method. This is useful for maintaining form inputs or scroll positions. ```javascript import { router } from '@inertiajs/svelte' router.get('/users', { search: 'John' }, { preserveState: true }) ``` -------------------------------- ### Programmatic Instant Visit Source: https://inertia-rails.dev/guide/instant-visits Initiate an instant visit programmatically using `router.visit()` with the `component` option. This allows for instant navigation triggered by custom logic. ```javascript router.visit('/dashboard', { component: 'Dashboard', }) ``` -------------------------------- ### Import NProgress and Inertia Router (Svelte) Source: https://inertia-rails.dev/guide/progress-indicators Import the NProgress library and the Inertia router for Svelte applications. ```javascript import NProgress from 'nprogress' import { router } from '@inertiajs/svelte' ``` -------------------------------- ### Preserve State with get Method (React) Source: https://inertia-rails.dev/guide/manual-visits Use this when you need to preserve the component's state when using the `get` method. This is useful for maintaining form inputs or scroll positions. ```javascript import { router } from '@inertiajs/react' router.get('/users', { search: 'John' }, { preserveState: true }) ``` -------------------------------- ### Preserve State with get Method (Vue) Source: https://inertia-rails.dev/guide/manual-visits Use this when you need to preserve the component's state when using the `get` method. This is useful for maintaining form inputs or scroll positions. ```javascript import { router } from '@inertiajs/vue3' router.get('/users', { search: 'John' }, { preserveState: true }) ``` -------------------------------- ### Initialize Inertia App (Vue) Source: https://inertia-rails.dev/guide/client-side-setup Update your main JavaScript file to boot your Inertia app using the Vue 3 adapter. The Vite plugin handles page resolution and mounting automatically. ```javascript import { createInertiaApp } from '@inertiajs/vue3' createInertiaApp() ``` -------------------------------- ### Check if Progress Bar Started in Progress Event Source: https://inertia-rails.dev/guide/progress-indicators Add a check within the 'progress' event listener to ensure NProgress has started before updating its progress, preventing issues if the visit finishes before the timeout. ```javascript router.on('progress', (event) => { if (!NProgress.isStarted()) { return } // ... }) ``` -------------------------------- ### Svelte File Upload Example with Inertia Form Helper Source: https://inertia-rails.dev/guide/file-uploads A Svelte component demonstrating file upload using Inertia's `useForm` helper. It includes a text input for name and a file input for avatar, with progress tracking. ```svelte
(form.avatar = e.target.files[0])} /> {#if form.progress} {form.progress.percentage}% {/if}
``` -------------------------------- ### Check if Progress Bar Started in Finish Event Source: https://inertia-rails.dev/guide/progress-indicators Add a check within the 'finish' event listener to ensure NProgress has actually started before attempting to finalize it, preventing issues if the visit finishes before the timeout. ```javascript router.on('finish', (event) => { clearTimeout(timeout) if (!NProgress.isStarted()) { return } // ... }) ``` -------------------------------- ### Rails Controller Authorization Example Source: https://inertia-rails.dev/guide/authorization Pass authorization results as props to your Inertia page. This example uses the Action Policy gem to check if the current user can create a user and edit individual users. ```ruby class UsersController < ApplicationController def index render inertia: { can: { create_user: allowed_to?(:create, User) }, users: User.all.map do |user| user.as_json( only: [:id, :first_name, :last_name, :email] ).merge( can: { edit_user: allowed_to?(:edit, user) } ) end } end end ``` -------------------------------- ### Use Axios with a Custom Instance Source: https://inertia-rails.dev/guide/client-side-setup Provide a pre-configured Axios instance to the `axiosAdapter` for more granular control over HTTP requests. ```javascript import axios from 'axios' import { axiosAdapter } from '@inertiajs/core' const instance = axios.create({ // ... }) createInertiaApp({ http: axiosAdapter(instance), // ... }) ``` -------------------------------- ### Configure Global Visit Options with Custom Headers (React) Source: https://inertia-rails.dev/guide/manual-visits Configure a `visitOptions` callback during app initialization to globally modify visit options for all requests. This example adds a custom header. ```javascript import { createInertiaApp } from '@inertiajs/react' import { createRoot } from 'react-dom/client' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { headers: { ...options.headers, 'X-Custom-Header': 'value', }, } }, }, }) ``` -------------------------------- ### Create New Rails App with Inertia (JavaScript) Source: https://inertia-rails.dev/cookbook/integrating-shadcn-ui Use this command to create a new Rails application with Inertia, React, Vite, and Tailwind CSS pre-configured, using JavaScript. ```bash rails new -JA shadcn-inertia-rails cd shadcn-inertia-rails bundle add inertia_rails rails generate inertia:install --framework=react --vite --tailwind --no-interactive Installing Inertia's Rails adapter ... ``` -------------------------------- ### React: Prefetch on Mousedown Source: https://inertia-rails.dev/guide/prefetching Start prefetching data on mousedown instead of hover by setting prefetch to 'click'. ```jsx import { Link } from '@inertiajs/react' export default () => ( Users ) ``` -------------------------------- ### Configure Global Visit Options with Custom Headers (Vue) Source: https://inertia-rails.dev/guide/manual-visits Configure a `visitOptions` callback during app initialization to globally modify visit options for all requests. This example adds a custom header. ```javascript import { createApp, h } from 'vue' import { createInertiaApp } from '@inertiajs/vue3' createInertiaApp({ // ... defaults: { visitOptions: (href, options) => { return { headers: { ...options.headers, 'X-Custom-Header': 'value', }, } }, }, }) ``` -------------------------------- ### Vue: Prefetch on Mousedown Source: https://inertia-rails.dev/guide/prefetching Start prefetching data on mousedown instead of hover by setting prefetch to 'click'. ```vue ``` -------------------------------- ### Install inertia_rails Gem Source: https://inertia-rails.dev/guide/server-side-setup Add the Inertia.js server-side adapter gem to your Rails application's Gemfile. ```bash bundle add inertia_rails ``` -------------------------------- ### Configure Vite with SSR Entry Point Source: https://inertia-rails.dev/guide/server-side-rendering Configure the Vite plugin in vite.config.js to specify the SSR entry point. ```javascript // vite.config.js import inertia from '@inertiajs/vite' export default defineConfig({ plugins: [ // ... inertia({ ssr: { entry: 'entrypoints/inertia.js', }, }), ], }) ``` -------------------------------- ### Add NProgress Styles Source: https://inertia-rails.dev/guide/progress-indicators Include the NProgress CSS styles in your project, for example, by using a CDN link. ```html ``` -------------------------------- ### Initial HTML Response Example Source: https://inertia-rails.dev/guide/the-protocol The first request to an Inertia app receives a standard HTML response. This includes site assets, a root div, and a script tag containing the initial page object as JSON. ```http REQUEST GET: https://example.com/events/80 Accept: text/html, application/xhtml+xml RESPONSE HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 My app
``` -------------------------------- ### Customize Validation Timeout Source: https://inertia-rails.dev/guide/forms Set a custom validation timeout for form requests. This example shows how to set it to 500ms. ```js const form = useForm('post', '/users', { name: '', }).setValidationTimeout(500) ``` ```js const form = useForm('post', '/users', { name: '', }) form.setValidationTimeout(500) ``` ```js const form = useForm('post', '/users', { name: '', }) form.setValidationTimeout(500) ``` -------------------------------- ### Configure JavaScript Path Aliases for shadcn/ui Source: https://inertia-rails.dev/cookbook/integrating-shadcn-ui Create a jsconfig.json file to configure path aliases for integrating shadcn/ui components when using JavaScript. This simplifies component imports. ```json { "compilerOptions": { "baseUrl": "./app/frontend", "paths": { "@/*": ["./*"] } } } ``` -------------------------------- ### Configure Babel for Dynamic Imports Source: https://inertia-rails.dev/guide/code-splitting Create a `.babelrc` file and add `@babel/plugin-syntax-dynamic-import` to enable dynamic imports in your project. ```json { "plugins": ["@babel/plugin-syntax-dynamic-import"] } ``` -------------------------------- ### Controller Action Validation (Bad Example) Source: https://inertia-rails.dev/guide/precognition Demonstrates an incorrect usage of precognition within a controller action, which will raise a `DoublePrecognitionError`. ```ruby def create precognition!(@user) precognition!(@profile) # Error! end ``` -------------------------------- ### Vue: Basic HTTP Request with useHttp Source: https://inertia-rails.dev/guide/http-requests Demonstrates how to use the useHttp hook in Vue to make a GET request to an API endpoint. It includes handling initial data, updating state, and processing feedback. ```vue ``` -------------------------------- ### Implement Manual Mode Infinite Scroll with Slots Source: https://inertia-rails.dev/guide/infinite-scroll Use manual mode to control content loading via '#previous' and '#next' slots. This example shows how to trigger loading with buttons. ```svelte {#snippet previous({ hasMore, fetch, loading })} {#if hasMore} {/if} {/snippet} {#each users as user (user.id)}
{user.name}
{/each} {#snippet next({ hasMore, fetch, loading })} {#if hasMore} {/if} {/snippet}
``` -------------------------------- ### Import NProgress and Inertia Router (Vue) Source: https://inertia-rails.dev/guide/progress-indicators Import the NProgress library and the Inertia router for Vue 3 applications. ```javascript import NProgress from 'nprogress' import { router } from '@inertiajs/vue3' ``` -------------------------------- ### Simulating PUT/PATCH/DELETE with POST for File Uploads Source: https://inertia-rails.dev/guide/file-uploads Workaround for multipart limitations with PUT, PATCH, or DELETE requests. Use `_method` attribute in a POST request to have the framework handle it as the intended HTTP method. ```js import { router } from '@inertiajs/vue3' router.post(`/users/${user.id}`, { _method: 'put', avatar: form.avatar, }) ``` ```js import { router } from '@inertiajs/react' router.post(`/users/${user.id}`, { _method: 'put', avatar: form.avatar, }) ``` ```js import { router } from '@inertiajs/svelte' router.post(`/users/${user.id}`, { _method: 'put', avatar: form.avatar, }) ``` -------------------------------- ### Configure Inertia with Modal Plugin for React Source: https://inertia-rails.dev/cookbook/inertia-modal Update your Inertia app setup in React to include the modal plugin for rendering modals. ```javascript // frontend/entrypoints/inertia.js import { createInertiaApp } from '@inertiajs/react' import { createElement } from 'react' // [!code --] import { renderApp } from '@inertiaui/modal-react' // [!code ++] import { createRoot } from 'react-dom/client' createInertiaApp({ resolve: (name) => { const pages = import.meta.glob('../pages/**/*.jsx', { eager: true }) return pages[`../pages/${name}.jsx`] }, setup({ el, App, props }) { const root = createRoot(el) root.render(createElement(App, props)) // [!code --] root.render(renderApp(App, props)) // [!code ++] }, }) ``` -------------------------------- ### Svelte: Basic HTTP Request with useHttp Source: https://inertia-rails.dev/guide/http-requests Illustrates the use of the useHttp hook in Svelte for performing a GET request. It includes binding input values, initiating the search, and conditionally rendering a loading message. ```svelte {#if http.processing}
Searching...
{/if} ``` -------------------------------- ### Configure Inertia with Modal Plugin for Vue Source: https://inertia-rails.dev/cookbook/inertia-modal Update your Inertia app setup in Vue to include the modal plugin for rendering modals. ```javascript // frontend/entrypoints/inertia.js import { createApp, h } from 'vue' import { createInertiaApp } from '@inertiajs/vue3' import { renderApp } from '@inertiaui/modal-vue' // [!code ++] createInertiaApp({ resolve: (name) => { const pages = import.meta.glob('../pages/**/*.vue', { eager: true }) return pages[`../pages/${name}.vue`] }, setup({ el, App, props, plugin }) { createApp({ render: () => h(App, props) }) // [!code --] createApp({ render: renderApp(App, props) }) // [!code ++] .use(plugin) .mount(el) }, }) ```