### Usage Example Source: https://v2.solidjs.com/reference/solid-js/advanced/specialized-reactivity/create-tracked-effect Example demonstrating dynamic subscription to a node's change event with cleanup. ```javascript createTrackedEffect(() => { const target = focusedNode(); if (!target) return; const handler = () => log(target.value()); target.on("change", handler); return () => target.off("change", handler); }); ``` -------------------------------- ### Install @solidjs/meta Source: https://v2.solidjs.com/building-apps/head-and-metadata Commands to install the @solidjs/meta package using various package managers. ```bash npm i @solidjs/meta ``` ```bash pnpm i @solidjs/meta ``` ```bash yarn add @solidjs/meta ``` ```bash bun i @solidjs/meta ``` ```bash deno add npm:@solidjs/meta ``` -------------------------------- ### Configure Node start script Source: https://v2.solidjs.com/building-apps/deployment Defines the start command in package.json to run the Node server with environment file support. ```json { "scripts": { "start": "node --env-file-if-exists=.env server.js" } } ``` -------------------------------- ### Install Browser Testing Dependencies Source: https://v2.solidjs.com/guides/testing Install the required Vitest, Playwright, and testing library packages, then initialize the Chromium browser. ```bash pnpm add -D vitest@^4.0.0 jsdom@^25.0.1 @solidjs/testing-library@1.0.0-beta.2 @testing-library/jest-dom@^6.6.3 @vitest/browser-playwright@^4.0.0 playwright@^1.56.0 pnpm exec playwright install chromium ``` -------------------------------- ### Switch usage example Source: https://v2.solidjs.com/reference/solid-js/components-jsx/switch-and-match Example demonstrating conditional rendering with Switch and Match components. ```jsx }> ``` -------------------------------- ### Configure serverFunctions Source: https://v2.solidjs.com/reference/vite-plugin-solid/server-functions Example configuration for the serverFunctions plugin. ```javascript serverFunctions: { configure: "./src/server-config.ts", } ``` -------------------------------- ### Creating and Using a Router Instance Source: https://v2.solidjs.com/reference/solid-router/router-factory Example of initializing a router and using it as a component. ```typescript const Router = createRouter({ routes: [{ path: "/", component: Home }], }); {(props) =>
{props.children}
}
; ``` -------------------------------- ### Define Setup Function Type Source: https://v2.solidjs.com/reference/vite-plugin-solid/start The signature for the setup function used to prepare the application before SSR. ```typescript type Setup = ( event: RequestEvent, App: Component ) => Component | void | Promise; ``` -------------------------------- ### Configure start.setup in SolidStart Source: https://v2.solidjs.com/building-apps/app-structure Defines the server-only setup module path within the SolidStart configuration object. ```javascript solid({ start: { setup: "./src/setup.tsx", }, ssr: true, }); ``` -------------------------------- ### Registering Extensions Source: https://v2.solidjs.com/reference/vite-plugin-solid/options Example of registering additional file extensions for the plugin. ```javascript solidPlugin({ extensions: [".mdx", [".page", { typescript: true }]], }); ``` -------------------------------- ### Install Netlify Vite Plugin Source: https://v2.solidjs.com/building-apps/deployment Install the Netlify plugin as a development dependency using your preferred package manager. ```bash npm i @netlify/vite-plugin -D ``` ```bash pnpm i @netlify/vite-plugin -D ``` ```bash yarn add @netlify/vite-plugin -D ``` ```bash bun i @netlify/vite-plugin -d ``` ```bash deno add npm:@netlify/vite-plugin -D ``` -------------------------------- ### Initialize SolidJS project with npm Source: https://v2.solidjs.com/getting-started/quick-start Use this command to start a new project using the npm package manager. ```bash npm init solid@latest ``` -------------------------------- ### Configure client start mode Source: https://v2.solidjs.com/reference/vite-plugin-solid/start Enables client-side rendering and shell serving for development and production builds. ```javascript solidPlugin({ start: true }); ``` -------------------------------- ### Initialize SolidJS project with alternative package managers Source: https://v2.solidjs.com/getting-started/quick-start Use these commands to start a new project using pnpm, yarn, or bun. ```bash pnpm create solid@latest yarn create solid@latest bun create solid@latest ``` -------------------------------- ### Match usage example Source: https://v2.solidjs.com/reference/solid-js/components-jsx/switch-and-match Example showing Match components inside a Switch, utilizing function children for narrowed values. ```jsx }> {(u) => } ``` -------------------------------- ### Example of createReaction with signal tracking Source: https://v2.solidjs.com/reference/solid-js/advanced/specialized-reactivity/create-reaction Shows how to track a signal and re-arm the reaction after a change occurs. ```javascript const [count, setCount] = createSignal(0); const track = createReaction(() => { console.log("count changed once, re-arm to listen again"); track(() => count()); // re-arm }); track(() => count()); // initial arm setCount(1); // logs once, reaction re-armed for next change ``` -------------------------------- ### Install Nitro Source: https://v2.solidjs.com/building-apps/deployment Install the Nitro package using your preferred package manager. ```bash npm i nitro ``` ```bash pnpm i nitro ``` ```bash yarn add nitro ``` ```bash bun i nitro ``` ```bash deno add npm:nitro ``` -------------------------------- ### Enable Start Mode in Vite Source: https://v2.solidjs.com/building-apps/app-structure Configure the SolidJS Vite plugin to enable start mode, which manages application entries and build processes. ```javascript import { defineConfig } from "vite"; import solid from "@solidjs/vite-plugin"; export default defineConfig({ plugins: [solid({ start: true })], }); ``` -------------------------------- ### Install Solid Router Source: https://v2.solidjs.com/routing/solid-router/setup Use pnpm to add the next version of the Solid Router package. ```bash pnpm add @solidjs/router@next ``` -------------------------------- ### Install Cloudflare Vite Plugin Source: https://v2.solidjs.com/building-apps/deployment Install the Cloudflare plugin and Wrangler CLI as development dependencies. ```bash npm i @cloudflare/vite-plugin wrangler -D ``` ```bash pnpm i @cloudflare/vite-plugin wrangler -D ``` ```bash yarn add @cloudflare/vite-plugin wrangler -D ``` ```bash bun i @cloudflare/vite-plugin wrangler -d ``` ```bash deno add npm:@cloudflare/vite-plugin wrangler -D ``` -------------------------------- ### Configure SSR start mode Source: https://v2.solidjs.com/reference/vite-plugin-solid/start Enables server-side rendering with streaming support and server bundle generation. ```javascript solidPlugin({ start: true, ssr: true }); ``` -------------------------------- ### Basic For component usage Source: https://v2.solidjs.com/reference/solid-js/components-jsx/for Example of rendering a list of items with a fallback for empty states. ```jsx No items}> {(item, index) =>
{item.label}
}
``` -------------------------------- ### Optimistic store usage examples Source: https://v2.solidjs.com/reference/solid-js/stores/create-optimistic-store Demonstrates initializing an optimistic store and performing optimistic mutations like adding and removing items. ```typescript const [todos, setTodos] = createOptimisticStore([]); // Mutation: optimistic add, then in-place reconcile to the saved row. const addTodo = action(function* (text: string) { const tempId = crypto.randomUUID(); setTodos((t) => { t.push({ id: tempId, text, pending: true }); }); const saved = yield api.createTodo(text); setTodos((t) => { const i = t.findIndex((x) => x.id === tempId); if (i >= 0) t[i] = saved; }); }); // Return form: filter is the natural shape for removal. const removeTodo = action(function* (id: string) { setTodos((t) => t.filter((x) => x.id !== id)); yield api.removeTodo(id); }); ``` -------------------------------- ### Server Rendering with Head Source: https://v2.solidjs.com/building-apps/head-and-metadata Example of streaming the document head during server-side rendering. ```javascript import { renderToStream } from "@solidjs/web"; import App from "./App"; // ... within the context of a request ... renderToStream(() => ).pipe(res); ``` -------------------------------- ### StartOptions Interface Source: https://v2.solidjs.com/reference/vite-plugin-solid/start The StartOptions interface defines the configuration object passed to the solidPlugin start option to customize the serving layer. ```APIDOC ## StartOptions Interface ### Description Configuration object for the serving layer enabled by `solidPlugin({ start })`. All paths are resolved relative to the Vite root. ### Properties - **app** (string) - Optional - Path to the application file. - **entryServer** (string) - Optional - Path to the server entry file. - **entryClient** (string) - Optional - Path to the client entry file. - **document** (string) - Optional - Path to the document template file. - **middleware** (string) - Optional - Path to the middleware file. - **setup** (string) - Optional - Path to the setup file. - **env** (boolean | string) - Optional - Environment configuration. - **external** (boolean) - Optional - Whether to treat dependencies as external. ``` -------------------------------- ### Usage examples for createProjection Source: https://v2.solidjs.com/reference/solid-js/stores/create-projection Demonstrates both the mutation form for updating fields and the return form for deriving collections. ```typescript // Mutation form — update individual fields on the draft. const summary = createProjection<{ total: number; active: number }>( (draft) => { draft.total = users().length; draft.active = users().filter((u) => u.active).length; }, { total: 0, active: 0 } ); // Return form — produce a derived collection. Reconciled by `id` so each // surviving user keeps the same store identity across recomputes. const activeUsers = createProjection( () => allUsers().filter((u) => u.active), [] ); ``` -------------------------------- ### createAPIHandler usage Source: https://v2.solidjs.com/reference/filesystem-routing/api Example of initializing the API handler with virtual file routes. ```typescript import routes from "virtual:file-routes"; import { createAPIHandler } from "filesystem-routing/api"; export default [createAPIHandler(routes)]; ``` -------------------------------- ### Usage example for optimistic updates Source: https://v2.solidjs.com/reference/solid-js/reactivity/create-optimistic Demonstrates initializing the signal and performing an optimistic update followed by reconciliation. ```typescript const [todos, setTodos] = createOptimistic(initialTodos); const addTodo = action(function* (text: string) { const tempId = crypto.randomUUID(); setTodos((t) => [...t, { id: tempId, text, pending: true }]); // optimistic const saved = yield api.createTodo(text); setTodos((t) => t.map((x) => (x.id === tempId ? saved : x))); // reconcile }); ``` -------------------------------- ### Component-level setup and teardown Source: https://v2.solidjs.com/reference/solid-js/lifecycle-actions/on-settled Use this pattern to subscribe to external sources on mount and unsubscribe on disposal. Returning a cleanup function from the callback handles the teardown logic. ```typescript // Component-level setup + teardown — replaces onMount + onCleanup. // Subscribe to an external source on mount, unsubscribe on dispose. function useViewportWidth() { const [width, setWidth] = createSignal(window.innerWidth); onSettled(() => { const onResize = () => setWidth(window.innerWidth); window.addEventListener("resize", onResize); return () => window.removeEventListener("resize", onResize); }); return width; } ``` -------------------------------- ### Initialize FlatFileSystemRouter Source: https://v2.solidjs.com/reference/filesystem-routing/conventions Defines the router class for flat filesystem structures and provides a Vite integration example. ```typescript import { FlatFileSystemRouter } from "filesystem-routing"; class FlatFileSystemRouter extends PageFileSystemRouter; ``` ```typescript import { resolve } from "node:path"; import { FlatFileSystemRouter } from "filesystem-routing"; import { fileRoutes } from "filesystem-routing/vite"; fileRoutes({ router: new FlatFileSystemRouter({ dir: resolve("src/routes"), extensions: ["js", "jsx", "ts", "tsx"], }), }); ``` -------------------------------- ### Per-route favicon example Source: https://v2.solidjs.com/reference/solid-meta/link Demonstrates dynamic favicon switching based on reactive props. ```typescript import { Link } from "@solidjs/meta"; export default function Inbox(props: { unread: () => number }) { return ( 0 ? "/favicon-badge.ico" : "/favicon.ico"} /> ); } ``` -------------------------------- ### Install testing dependencies Source: https://v2.solidjs.com/guides/testing Add the required development dependencies for Vitest, jsdom, and Solid Testing Library to your project. ```bash pnpm add -D vitest@^4.0.0 jsdom@^25.0.1 @solidjs/testing-library@1.0.0-beta.2 @testing-library/jest-dom@^6.6.3 ``` -------------------------------- ### Dynamic Component Usage Source: https://v2.solidjs.com/reference/solid-web/components/dynamic-component Example of rendering a component dynamically based on a condition. ```jsx ``` -------------------------------- ### Usage Examples for renderToStream Source: https://v2.solidjs.com/reference/solid-web/rendering-ssr/render-to-stream Demonstrates how to use renderToStream with Node.js, Web environments like Workers or Deno, and how to await the fully settled HTML string. ```typescript import { renderToStream } from "@solidjs/web"; // Node: renderToStream(() => ).pipe(res); // Web (Workers / Deno): return new Response(renderToStream(() => ).readable); // Fully settled string: const html = await renderToStream(() => ); ``` -------------------------------- ### Handle SSR requests Source: https://v2.solidjs.com/reference/vite-plugin-solid/modules The entry point for the start mode server build to process requests and return page responses. ```typescript export function handleRequest( request: Request, options?: { clientEntry?: string; context?: Record; responseInit?: ResponseInit; serverFunctions?: Record; } ): Promise; ``` -------------------------------- ### Basic usage of Repeat Source: https://v2.solidjs.com/reference/solid-js/components-jsx/repeat Example showing how to render a list of items using the Repeat component with a fallback for empty states. ```jsx No items}> {(index) =>
{items[index]}
}
``` -------------------------------- ### Create a detached reactive root Source: https://v2.solidjs.com/reference/solid-js/advanced/owner-introspection/create-root Example of initializing a reactive scope with createRoot and manually disposing of it later. ```javascript const dispose = createRoot((dispose) => { const [n, setN] = createSignal(0); createEffect( () => n(), (value) => console.log(value) ); setInterval(() => setN((x) => x + 1), 1000); return dispose; }); // Later, to tear everything down: dispose(); ``` -------------------------------- ### Basic usage of repeat Source: https://v2.solidjs.com/reference/solid-js/advanced/jsx-component-primitives/repeat Example showing how to use repeat with a count accessor and a fallback value. ```javascript const view = repeat(count, (i) => `Item ${i}`, { fallback: () => "empty" }); ``` -------------------------------- ### Configure Solid 2 Vite plugin Source: https://v2.solidjs.com/migration/from-solid-start Example configuration for the Solid 2 Vite plugin, including middleware, SSR, and server function settings. ```typescript import { fileRoutes } from "filesystem-routing/vite"; import { defineConfig } from "vite"; import solid from "@solidjs/vite-plugin"; export default defineConfig({ plugins: [ solid({ start: { middleware: "./src/middleware.ts", }, ssr: true, serverFunctions: true, extensions: [".jsx", ".tsx"], }), fileRoutes({ httpMethods: true }), ], }); ``` -------------------------------- ### Create primitive context with default Source: https://v2.solidjs.com/reference/solid-js/components-context/create-context Example of a context with a default value, useful for static fallbacks like themes. ```javascript // Primitive default — falls back to "light" outside a Provider. const ThemeContext = createContext<"light" | "dark">("light"); function Button() { const theme = useContext(ThemeContext); // "light" | "dark" return ; } ``` -------------------------------- ### Mount Without Start Mode Source: https://v2.solidjs.com/routing/solid-router/setup Render the application component from a client entry for transform-only Vite applications. ```tsx // src/index.tsx import { render } from "@solidjs/web"; import App from "./App"; render(() => , document.getElementById("app")!); ``` -------------------------------- ### Create reactive context Source: https://v2.solidjs.com/reference/solid-js/components-context/create-context Example of a default-less context used for reactive state, which throws an error if accessed without a provider. ```javascript // Reactive payload — default-less, throws if no Provider. type TodosCtx = readonly [Store, TodoActions]; const TodosContext = createContext(); function App() { return ( ); } function TodoList() { const [todos, { addTodo }] = useContext(TodosContext); // typed as TodosCtx // ... } ``` -------------------------------- ### Ref Usage Example Source: https://v2.solidjs.com/reference/solid-js/types/component-types Example of using the Ref type within a component definition. ```typescript Component<{ ref: Ref }>; ``` -------------------------------- ### Initialize and update a store Source: https://v2.solidjs.com/reference/solid-js/stores/create-store Demonstrates creating a store and performing updates using both mutation and return-value patterns. ```javascript const [state, setState] = createStore({ user: { name: "Ada", age: 36 }, todos: [] as { id: string; text: string; done: boolean }[], }); // Canonical: mutate the draft in place. setState((s) => { s.user.age = 37; }); setState((s) => { s.todos.push({ id: "1", text: "x", done: false }); }); // Return form: reach for it when mutation is awkward. setState((s) => s.todos.filter((t) => !t.done)); // remove items setState((s) => ({ ...s, user: { name: "Grace", age: 85 } })); // shallow replace ``` -------------------------------- ### Optimistic update with action Source: https://v2.solidjs.com/reference/solid-js/lifecycle-actions/action Example of using action with createOptimisticStore to handle optimistic UI updates and server synchronization. ```typescript const [todos, setTodos] = createOptimisticStore([]); const addTodo = action(async function* (text: string) { const tempId = crypto.randomUUID(); setTodos((t) => { t.push({ id: tempId, text, pending: true }); }); // optimistic const saved = await api.createTodo(text); // network round-trip, typed yield; // re-enter the transaction setTodos((t) => { const i = t.findIndex((x) => x.id === tempId); if (i >= 0) t[i] = saved; }); return saved; }); await addTodo("buy milk"); ``` -------------------------------- ### Conditional Rendering with Show Source: https://v2.solidjs.com/reference/solid-js/components-jsx/show Example of using the Show component to render a greeting if a user exists, or a sign-in component otherwise. ```jsx }> {(u) => } ``` -------------------------------- ### Custom directive example Source: https://v2.solidjs.com/reference/solid-js/advanced/specialized-reactivity/create-render-effect Example of using createRenderEffect to bind an element's textContent to a reactive source. ```typescript // Custom directive: bind an element's textContent to a reactive source. function bindText(el: HTMLElement, source: () => string) { createRenderEffect( () => source(), (value) => { el.textContent = value; } ); } ``` -------------------------------- ### Build the application Source: https://v2.solidjs.com/building-apps/deployment Execute the configured Vite build process to generate the production assets. ```bash pnpm build ``` -------------------------------- ### Importing StartOptions Source: https://v2.solidjs.com/reference/vite-plugin-solid/start Import the solidPlugin and the StartOptions type definition from the @solidjs/vite-plugin package. ```typescript import solidPlugin, { type StartOptions } from "@solidjs/vite-plugin"; ``` -------------------------------- ### Declare an HTTP GET server function Source: https://v2.solidjs.com/building-apps/server-functions Use the GET wrapper for safe, idempotent read operations. Arguments are passed via the URL, so avoid sensitive data. ```typescript import { GET } from "@solidjs/web/server-functions"; export const getUser = GET(async (id: string) => { "use server"; return database.users.find(id); }); ``` -------------------------------- ### Basic createReaction usage Source: https://v2.solidjs.com/reference/solid-js/advanced/specialized-reactivity/create-reaction Demonstrates the initialization and manual re-arming pattern of createReaction. ```javascript const track = createReaction(effectFn, options?: EffectOptions); track(() => { // reactive reads }); ``` -------------------------------- ### Defining fileRoutes Source: https://v2.solidjs.com/reference/solid-router/filesystem Type definition and usage example for the fileRoutes function. ```typescript function fileRoutes( entries: T ): FileRoutesFrom; ``` ```typescript import { pageRoutes } from "virtual:file-routes"; import { createRouter } from "@solidjs/router"; import { fileRoutes } from "@solidjs/router/fs"; const Router = createRouter({ routes: fileRoutes(pageRoutes), }); ``` -------------------------------- ### Using latest in a component Source: https://v2.solidjs.com/reference/solid-js/reactivity/latest Example of wrapping a reactive variable with latest. ```typescript const preview = () => latest(user); ``` -------------------------------- ### Using useLinkState Source: https://v2.solidjs.com/reference/solid-router/navigation Get the active, current, and pending state of a link. ```typescript function useLinkState( href: () => string | TypedPath, options?: { end?: boolean } ): LinkState; ``` ```typescript interface LinkState { active: () => boolean; current: () => boolean; pending: () => boolean; } ``` -------------------------------- ### Import getObserver Source: https://v2.solidjs.com/reference/solid-js/advanced/owner-introspection/get-observer Import the function from the solid-js package. ```javascript import { getObserver } from "solid-js"; ``` -------------------------------- ### Example of a typed route component Source: https://v2.solidjs.com/reference/solid-router/routes-and-paths A component typed with a specific path definition. ```typescript const User: RouteComponent = props => (

{props.params.id}

); ``` -------------------------------- ### Preview production build Source: https://v2.solidjs.com/building-apps/deployment Commands to build the project and serve the production artifacts using Vite preview. ```bash pnpm build pnpm exec vite preview ``` ```bash pnpm build pnpm serve ``` -------------------------------- ### Configure Solid Router Source: https://v2.solidjs.com/migration/from-solid-start Initialize the router using file-based routes from the virtual file-routes module. ```typescript import { pageRoutes } from "virtual:file-routes"; import { createRouter } from "@solidjs/router"; import { fileRoutes } from "@solidjs/router/fs"; export const Router = createRouter({ routes: fileRoutes(pageRoutes), }); ``` -------------------------------- ### Usage of Router.paths Source: https://v2.solidjs.com/reference/solid-router/routes-and-paths Examples of generating paths using the typed Router.paths object. ```typescript Router.paths.users(42).settings(); Router.paths.search({ q: "solid" }, "results"); String(Router.paths.about); ``` -------------------------------- ### Async memo usage Source: https://v2.solidjs.com/reference/solid-js/reactivity/create-memo Example of an asynchronous memo that handles pending states. ```typescript // Async memo — reads surface as pending inside const user = createMemo(async () => { const res = await fetch(`/users/${id()}`); return res.json(); }); ``` -------------------------------- ### Replace createResource with async memo Source: https://v2.solidjs.com/migration/from-solid-1 Transition from Solid 1 resource patterns to Solid 2 async memo computations. ```javascript // Solid 1 const [user] = createResource(userId, fetchUser); // Solid 2 const user = createMemo(() => fetchUser(userId())); ``` -------------------------------- ### Use innerHTML with reactive content Source: https://v2.solidjs.com/reference/solid-web/jsx-properties/inner-html Example of using innerHTML with a reactive memoized value. ```javascript import { createMemo } from "solid-js"; const html = createMemo(() => sanitize(renderMarkdown(props.source))); return
; ``` -------------------------------- ### StartOptions Interface Definition Source: https://v2.solidjs.com/reference/vite-plugin-solid/start The configuration interface for the serving layer. All paths must be relative to the Vite root. ```typescript interface StartOptions { app?: string; entryServer?: string; entryClient?: string; document?: string; middleware?: string; setup?: string; env?: boolean | string; external?: boolean; } ``` -------------------------------- ### Canonical link example Source: https://v2.solidjs.com/reference/solid-meta/link Basic usage of the Link component to define a canonical URL. ```typescript import { Link } from "@solidjs/meta"; export default function Page() { return ; } ``` -------------------------------- ### Netlify Build Configuration Source: https://v2.solidjs.com/building-apps/deployment Set the build command and publish directory in your Netlify configuration. ```toml [build] command = "pnpm build" publish = "dist/client" ``` -------------------------------- ### Split Reactive Work Source: https://v2.solidjs.com/reference/solid-js/reactivity/create-effect Example of splitting reactive dependency tracking from side effects. ```javascript createEffect(() => signal(), value => doWork(value)) ``` -------------------------------- ### createStore(store, options?) Source: https://v2.solidjs.com/reference/solid-js/stores/create-store Creates a standard reactive store from an initial object value. ```APIDOC ## createStore(store, options?) ### Description Creates a reactive store from an initial object value. Returns a tuple containing the store accessor and a setter function. ### Parameters - **store** (NoFn | Store>) - Required - The initial state object. - **options** (StoreOptions & { shallow?: boolean }) - Optional - Configuration options including debug name and shallow reactivity settings. ### Return Value - **[store, setStore]** (StoreReturn) - A tuple containing the reactive store accessor and the setter function. ``` -------------------------------- ### Configure Environment Schema Source: https://v2.solidjs.com/reference/vite-plugin-solid/start Example of a default export for environment validation using Standard Schema. ```typescript export default { server: { DATABASE_URL: z.url(), }, client: { VITE_APP_NAME: z.string(), }, }; ``` -------------------------------- ### Basic Hydration Usage Source: https://v2.solidjs.com/reference/solid-web/rendering-ssr/hydrate Example of using hydrate to attach an App component to a DOM element. ```typescript import { hydrate } from "@solidjs/web"; const dispose = hydrate(() => , document.getElementById("root")!); ``` -------------------------------- ### Rendering a dynamic component Source: https://v2.solidjs.com/reference/solid-web/components/dynamic Example of using dynamic to render a component based on a reactive route. ```jsx const CurrentPage = dynamic(() => pages[route()]); return ; ``` -------------------------------- ### Defining route modules with defineFileRoute Source: https://v2.solidjs.com/reference/solid-router/filesystem Type definition and implementation example for defining route configurations. ```typescript function defineFileRoute< S extends string, T = unknown, const F = DefinedRouteFilters, Sch extends StandardSchemaV1 | undefined = undefined, >( path: S, config: { matchFilters?: F; preload?: (args: RoutePreloadFuncArgs>) => T; search?: Sch; info?: RouteInfo; } ): FileRouteConfig; ``` ```typescript export const route = defineFileRoute("/blog/:id", { matchFilters: { id: int }, preload: ({ params }) => getPost(params.id), }); export default function Post(props: RouteProps) { return

{props.data.title}

; } ``` -------------------------------- ### solidPlugin(options?: Partial) Source: https://v2.solidjs.com/reference/vite-plugin-solid/options Configures Solid compilation and returns the necessary Vite plugins. ```APIDOC ## solidPlugin(options) ### Description Configures Solid compilation and returns the Vite plugins needed by the selected modes. ### Signature `function solidPlugin(options?: Partial): Plugin[]` ### Options - **include** (FilterPattern) - Optional - Limits transformed files with Vite filter patterns. - **exclude** (FilterPattern) - Optional - Excludes files with Vite filter patterns. - **dev** (boolean) - Optional - Selects development exports of solid-js and @solidjs/web. - **ssr** (boolean) - Optional - Enables hydratable client output and SSR output. - **start** (boolean | StartOptions) - Optional - Enables start mode. - **compiler** ("babel" | "native") - Optional - Selects the JSX compiler. Defaults to "native". - **hot** (boolean) - Optional - Deprecated. Use refresh.disabled instead. - **extensions** ((string | [string, ExtensionOptions])[]) - Optional - Registers additional extensions for parsing. - **babel** (babel.TransformOptions | Function) - Optional - Merges Babel options into the transform. - **solid** (SolidOptions) - Optional - Overrides DOM Expressions compiler options. - **serverFunctions** (boolean | ServerFunctionsOptions) - Optional - Enables "use server" compilation. - **refresh** (RefreshOptions) - Optional - Configures development refresh transform settings. ``` -------------------------------- ### Import createStore Source: https://v2.solidjs.com/reference/solid-js/stores/create-store Import the createStore function from the solid-js package. ```javascript import { createStore } from "solid-js"; ``` -------------------------------- ### Import createRoot Source: https://v2.solidjs.com/reference/solid-js/advanced/owner-introspection/create-root Import the createRoot function from the solid-js package. ```javascript import { createRoot } from "solid-js"; ``` -------------------------------- ### Register jest-dom matchers Source: https://v2.solidjs.com/guides/testing Import the jest-dom matchers in your setup file to enable DOM-specific assertions. ```javascript import "@testing-library/jest-dom/vitest"; ``` -------------------------------- ### Importing Show Source: https://v2.solidjs.com/reference/solid-js/components-jsx/show Import the Show component from the solid-js package. ```javascript import { Show } from "solid-js"; ``` -------------------------------- ### Using clientOnly for Browser-Only Components Source: https://v2.solidjs.com/reference/solid-web/rendering-ssr/client-only Example of wrapping a component with clientOnly and providing a fallback for the server-side render. ```javascript const Chart = clientOnly(() => import("./Chart.jsx")); // Loading chart…} data={data()} /> ``` -------------------------------- ### Apply integer match filter Source: https://v2.solidjs.com/reference/solid-router/routes-and-paths Example of using the int filter to validate URL segments as integers. ```typescript import { int } from "@solidjs/router"; const route = defineRoute({ path: "/users/:id", matchFilters: { id: int }, }); ``` -------------------------------- ### Using useContext in a component Source: https://v2.solidjs.com/reference/solid-js/components-context/use-context Example of consuming a context within a component. This will throw an error if no provider is present. ```javascript const TodosContext = createContext(); function TodoList() { const [todos, { addTodo }] = useContext(TodosContext); // throws if no Provider // ... } ``` -------------------------------- ### Using NoHydration for Client-Only Widgets Source: https://v2.solidjs.com/reference/solid-js/advanced/manual-hydration/no-hydration Example of wrapping a client-only component to prevent server-side hydration interference. ```jsx // Mount a client-only widget that the server didn't render. The subtree // is left empty during hydration, then renders fresh once hydration ends. ``` -------------------------------- ### Initialize PageFileSystemRouter Source: https://v2.solidjs.com/reference/filesystem-routing/conventions Configures the router for nested filesystem structures. ```typescript import { PageFileSystemRouter, type PageFileSystemRouterConfig, } from "filesystem-routing"; class PageFileSystemRouter extends BaseFileSystemRouter { constructor(config: PageFileSystemRouterConfig); } ``` -------------------------------- ### Custom loading boundary component Source: https://v2.solidjs.com/reference/solid-js/advanced/jsx-component-primitives/create-loading-boundary An example of wrapping the primitive to create a custom loading boundary component. ```typescript // Custom boundary component built on top of the primitive. function MyLoading(props: { fallback: JSX.Element; children: JSX.Element }) { return createLoadingBoundary( () => props.children, () => props.fallback ) as unknown as JSX.Element; } ``` -------------------------------- ### Import onSettled Source: https://v2.solidjs.com/reference/solid-js/lifecycle-actions/on-settled Import the onSettled primitive from the solid-js package. ```typescript import { onSettled } from "solid-js"; ``` -------------------------------- ### Usage of createRevealOrder Source: https://v2.solidjs.com/reference/solid-js/advanced/jsx-component-primitives/create-reveal-order Example showing the primitive form used to coordinate sibling loading boundaries programmatically. ```javascript // Primitive form of `` — coordinate sibling loading boundaries // programmatically. App code uses the JSX `` component instead. // Both options are accessors so they can react to state changes. createRevealOrder(() => renderSiblings(), { order: () => mode(), collapsed: () => true, }); ``` -------------------------------- ### Custom Error Boundary with Telemetry Source: https://v2.solidjs.com/reference/solid-js/advanced/jsx-component-primitives/create-error-boundary Example of wrapping the primitive to create a custom boundary that logs errors. ```typescript // Custom boundary that wraps the primitive and adds telemetry. function TracedErrored(props: { fallback: (e: () => unknown) => JSX.Element; children: JSX.Element; }) { return createErrorBoundary( () => props.children, (err, reset) => { reportError(err()); return props.fallback(err); } ) as unknown as JSX.Element; } ``` -------------------------------- ### Configure filesystem routing Source: https://v2.solidjs.com/routing/solid-router/route-definitions Enable the filesystem-routing Vite plugin and use the @solidjs/router/fs adapter to convert generated routes. ```typescript // vite.config.ts import { defineConfig } from "vite"; import { fileRoutes as fileRoutesPlugin } from "filesystem-routing/vite"; import solid from "@solidjs/vite-plugin"; export default defineConfig({ plugins: [solid({ start: true }), fileRoutesPlugin()], }); ``` ```typescript import { pageRoutes } from "virtual:file-routes"; import { createRouter } from "@solidjs/router"; import { fileRoutes as routerFileRoutes } from "@solidjs/router/fs"; export const Router = createRouter({ routes: routerFileRoutes(pageRoutes), }); ``` -------------------------------- ### Create an async memo with pre-await dependency tracking Source: https://v2.solidjs.com/concepts/async-reactivity Ensure all reactive inputs are read before the first 'await' to correctly establish dependency edges for the computation. ```javascript const profile = createMemo(async () => { const userId = id(); const permission = permissions(); const response = await fetch(`/api/users/${userId}`); const user = await response.json(); return { user, permission }; }); ``` -------------------------------- ### Import createOptimisticStore Source: https://v2.solidjs.com/reference/solid-js/stores/create-optimistic-store Import the function from the solid-js package. ```typescript import { createOptimisticStore } from "solid-js"; ``` -------------------------------- ### Basic signal usage Source: https://v2.solidjs.com/reference/solid-js/reactivity/create-signal Demonstrates initializing a signal and using the accessor and setter. ```typescript const [count, setCount] = createSignal(0); count(); // 0 setCount(1); // explicit value setCount((c) => c + 1); // updater ``` -------------------------------- ### serverFunctions(options) Source: https://v2.solidjs.com/reference/vite-plugin-solid/server-functions Initializes the serverFunctions compiler plugin with optional configuration for runtime, manifest, and endpoint behavior. ```APIDOC ## function serverFunctions(options?: ServerFunctionsOptions): Plugin[] ### Description Configures the compiler to support "use server" directives. This function returns an array of Vite plugins. ### Parameters - **options** (ServerFunctionsOptions) - Optional - Configuration object for the plugin. ### ServerFunctionsOptions - **runtime** ({ server: string, client: string }) - Optional - Specifies runtime imports for server and client. - **manifest** (string) - Optional - Virtual module for side-effect imports. - **filter** (ServerFunctionsFilter) - Optional - Includes/excludes files for compilation. - **directive** (string) - Optional - The directive text (default: "use server"). - **endpoint** (string) - Optional - The request path for server functions. - **devMiddleware** (boolean) - Optional - Whether to install development middleware. - **configure** (string) - Optional - Path to a server-only configuration module. - **components** (boolean) - Optional - Experimental: enables server-function results containing components. ``` -------------------------------- ### Compare React and SolidJS event handling Source: https://v2.solidjs.com/migration/from-react Demonstrates the difference between React's useState and Solid's createSignal for managing input state. ```jsx const [query, setQuery] = useState(""); return ( setQuery(event.currentTarget.value)} /> ); ``` ```jsx const [query, setQuery] = createSignal(""); return ( setQuery(event.currentTarget.value)} /> ); ``` -------------------------------- ### Define and use a HeadTag Source: https://v2.solidjs.com/reference/solid-web/head/head-tag Example of defining a meta tag descriptor with a reactive content property and applying it with useHead. ```typescript const description: HeadTag = { tag: "meta", key: "page-description", props: { name: "description", content: () => summary(), }, }; useHead(description); ``` -------------------------------- ### fileRoutes(options?: FileRoutesOptions) Source: https://v2.solidjs.com/reference/filesystem-routing/vite Initializes the Vite plugin for filesystem routing. It scans the directory for route files, manages the virtual manifest, and handles code splitting and module exports. ```APIDOC ## fileRoutes(options?: FileRoutesOptions) ### Description Initializes the Vite plugin for filesystem routing. It scans the directory for route files, manages the virtual manifest, and handles code splitting and module exports. ### Parameters #### Options (FileRoutesOptions) - **dir** (string) - Optional - Specifies the route directory relative to the Vite root. Default: "src/routes" - **extensions** (string[]) - Optional - Specifies scanned extensions without leading dots. Default: ["js", "jsx", "ts", "tsx"] - **components** (boolean) - Optional - Controls whether page entries contain $component refs. Default: true - **httpMethods** (boolean | readonly string[]) - Optional - Recognizes specific HTTP method exports. Default: false - **toPath** (Function) - Optional - Overrides the default filename-to-path function. - **toRoute** (Function) - Optional - Overrides module-to-manifest conversion. - **router** (BaseFileSystemRouter) - Optional - Supplies a scanner and convention for environments. - **routers** (Record) - Optional - Supplies routers keyed by Vite environment name. - **moduleId** (string) - Optional - Specifies the virtual manifest module ID. Default: "virtual:file-routes" - **buildInputs** (string | string[]) - Optional - Names Vite environments whose builds add every delivered lazy module ref as a Rollup input. - **codeSplitting** (boolean) - Optional - Enables dynamic import() functions for route chunks. Default: true - **optimizeDepsExclude** (string[]) - Optional - Adds packages to Vite's dependency prebundle exclusion list. - **types** (boolean | string) - Optional - Writes a self-contained ambient declaration file. ``` -------------------------------- ### Using the Errored component with a fallback Source: https://v2.solidjs.com/reference/solid-js/components-jsx/errored Example of wrapping a component with Errored to handle errors and provide a reset trigger. ```jsx (
Error: {err().toString()}
)} >
``` -------------------------------- ### Import createContext Source: https://v2.solidjs.com/reference/solid-js/components-context/create-context Import the createContext function from the solid-js package. ```javascript import { createContext } from "solid-js"; ``` -------------------------------- ### Configure environment schema path Source: https://v2.solidjs.com/building-apps/environment Specify a custom path for the environment schema in the SolidStart Vite configuration. ```javascript solid({ start: { env: "./config/env.ts", }, }); ``` -------------------------------- ### createStore(initialValue) Source: https://v2.solidjs.com/reference/solid-js/stores/create-store Creates a deeply-reactive store from an initial value, wrapping it in a reactive proxy. ```APIDOC ## createStore(initialValue) ### Description Creates a deeply-reactive store backed by a Proxy. Reads track each property accessed, and only the parts that change trigger updates. ### Signature `createStore(initialValue)` ### Parameters - **initialValue** (any) - The initial state object or value to be wrapped in a reactive proxy. ``` -------------------------------- ### Basic mapArray Usage Source: https://v2.solidjs.com/reference/solid-js/advanced/jsx-component-primitives/map-array Example of using mapArray to transform an items list into a view with a fallback for empty states. ```javascript const view = mapArray(items, (item, index) => `${index()}: ${item.label}`, { fallback: () => "no items", }); ``` -------------------------------- ### Resolving a reactive expression Source: https://v2.solidjs.com/reference/solid-js/advanced/interop-async/resolve Example of using resolve to await a value from a reactive memo outside of a tracking scope. ```javascript const user = createMemo(() => fetch(`/users/${id()}`).then((r) => r.json())); // outside any reactive scope const initial = await resolve(() => user()); ``` -------------------------------- ### Import createMemo Source: https://v2.solidjs.com/reference/solid-js/reactivity/create-memo Required import from the solid-js package. ```typescript import { createMemo } from "solid-js"; ``` -------------------------------- ### Using flatten in a Custom Renderer Source: https://v2.solidjs.com/reference/solid-js/advanced/interop-async/flatten Example of using flatten to process children manually within a custom renderer. ```typescript // Custom renderer walking a children tree manually. Most authors should // use `children()` from solid-js, which memoizes the resolved value. function renderChildren(value: unknown): unknown { return flatten(value, { skipNonRendered: true }); } ``` -------------------------------- ### Configure test script Source: https://v2.solidjs.com/guides/testing Add the test command to your package.json file. ```json { "scripts": { "test": "vitest" } } ``` -------------------------------- ### Defining a social tag block Source: https://v2.solidjs.com/reference/solid-meta/head Example of using Head to group multiple meta and title tags for an article component. ```typescript import { Head, Meta, Title } from "@solidjs/meta"; export default function Article(props: { article: () => { title: string; image: string }; }) { return ( {props.article().title} ); } ``` -------------------------------- ### Importing clientOnly Source: https://v2.solidjs.com/reference/solid-web/rendering-ssr/client-only Import the clientOnly utility from the @solidjs/web package. ```javascript import { clientOnly } from "@solidjs/web"; ``` -------------------------------- ### Update useHead imports Source: https://v2.solidjs.com/migration/from-solid-meta Import useHead from @solidjs/web instead of @solidjs/meta. ```javascript import { useHead } from "@solidjs/web"; useHead({ tag: "meta", props: { name: "description", content: () => desc() } }); ``` -------------------------------- ### createStore(fn, store, options?) Source: https://v2.solidjs.com/reference/solid-js/stores/create-store Creates a derived or projected store that auto-fetches and reconciles data. ```APIDOC ## createStore(fn, store, options?) ### Description Creates a derived store that uses a function to fetch or compute state, initialized with a seed value. It supports keyed reconciliation for arrays. ### Parameters - **fn** ((store: T) => void | T | Promise | AsyncIterable) - Required - The derivation function. - **store** (Partial | Store>) - Required - The seed or initial state. - **options** (ProjectionOptions) - Optional - Configuration including key for reconciliation, shallow settings, and loading value behavior. ### Return Value - **[get, set]** (ProjectionStoreReturn) - A tuple containing the refreshable store accessor and the setter function. ``` -------------------------------- ### Use storePath for state updates Source: https://v2.solidjs.com/reference/solid-js/advanced/store-advanced/store-path Examples of using storePath to update nested state, filter arrays, or delete properties. ```typescript setState(storePath("user", "name", "Grace")); setState(storePath("todos", (todo) => !todo.done, "done", true)); setState(storePath("user", "nickname", storePath.DELETE)); ``` -------------------------------- ### Import createProjection Source: https://v2.solidjs.com/reference/solid-js/stores/create-projection Import the function from the solid-js package. ```typescript import { createProjection } from "solid-js"; ``` -------------------------------- ### createOptimisticStore(initialValue) Source: https://v2.solidjs.com/reference/solid-js/stores/create-optimistic-store Creates an optimistic store with an initial value. ```APIDOC ## createOptimisticStore(initialValue) ### Description Initializes a store that supports optimistic updates for collection-shaped data. ### Signature `createOptimisticStore(store: NoFn | Store>, options?: ProjectionOptions): [get: Store, set: StoreSetter]` ### Parameters - **store** (NoFn | Store>) - The initial state of the store. - **options** (ProjectionOptions) - Optional configuration for the store, such as the identity key. ### Return Value - **[get, set]** (Array) - Returns a tuple containing the store accessor and the setter function. ``` -------------------------------- ### Using omit in a Component Source: https://v2.solidjs.com/reference/solid-js/stores/omit Example of using omit to filter out handled props before spreading the remaining props onto an input element. ```tsx function Input( props: { label: string; value: string; onInput: (v: string) => void; } & JSX.HTMLAttributes ) { const rest = omit(props, "label", "value", "onInput"); return ( ); } ``` -------------------------------- ### Importing isServer Source: https://v2.solidjs.com/reference/solid-web/rendering-ssr/is-server Import the isServer constant from the @solidjs/web package. ```javascript import { isServer } from "@solidjs/web"; ``` -------------------------------- ### Run Browser Tests Source: https://v2.solidjs.com/guides/testing Execute the browser test suite once and exit. ```bash pnpm test --run ``` -------------------------------- ### Importing Meta Source: https://v2.solidjs.com/reference/solid-meta/meta Import the Meta component from the @solidjs/meta package. ```typescript import { Meta } from "@solidjs/meta"; ```