Install
spago install purs-solidFor a package set that predates the release, add purs-solid: 0.1.0 under workspace.extraPackages in spago.yaml, then run the same command.
Use Node.js 22.12 or later. Install the Solid 2 runtime and web renderer.
npm install solid-js@2 @solidjs/web@2Install Router and Meta when using Solid.Router and Solid.Meta.
npm install @solidjs/router@2 @solidjs/meta@2For compiled views or start mode, install the Git-hosted purs-solid/vite wrapper with the Vite and Solid plugin versions required by its v0.1.0 tag.
npm install --save-dev @solidjs/vite-plugin@3.0.0 vite@8.3.8 "git+https://github.com/arazorda/purs-solid.git#v0.1.0"Commit package-lock.json and use npm ci for repeatable installs.
Bundle development builds with the development export condition to get Solid's diagnostics.
Components and elements
A Component is a function from a props record to a view, built in Setup. Elements take a record of props and their children; Component.element renders a component with its props.
import Data.Tuple.Nested ((/\))
import Solid.Component as Component
import Solid.DOM.HTML as H
import Solid.Reactivity (createMemo)
import Solid.Signal (createSignal, modify_)
counter :: Component.Component {}
counter = Component.component \_ -> do
count /\ setCount <- createSignal 0
doubled <- createMemo ((_ * 2) <$> count)
pure $ H.div { class: "counter" }
[ H.button
{ onClick: \_ -> modify_ setCount (_ + 1)
, class: { big: (_ > 3) <$> count }
}
"+1"
, H.span {} (show <$> count)
, H.small {} ((\n -> "doubled: " <> show n) <$> doubled)
]Each field is checked against the element's row, so href only type-checks on elements that have it. Attributes take a value or an Accessor; event fields take a handler for the row's event type. Children are one element, text (a String or an Accessor String), or an array of elements; mix text into an array with text. Void elements like H.img take only the record.
card :: Accessor String -> Accessor Boolean -> JSX
card title selected =
H.article { class: { card: true, selected }, "data-testid": "card" }
[ H.h2 {} title
, H.a { href: "/docs", title } "Read more"
, H.img { src: "/logo.svg", alt: "" }
]Beyond the element's own attributes, a record can have:
ref: gets the element once it's created, typed by the element.class: a string, or a record of class toggles.style: CSS text, or a record of properties.bindValue/bindChecked: bind a field's value or a checkbox to a signal both ways.roleand thearia-*attributes, typed by WAI-ARIA 1.2 (Solid.DOM.Aria).data-*attributes, case-sensitiveon:namelisteners, andinnerHTMLortextContent.
search :: Signal String -> (String -> Effect Unit) -> JSX
search query submit =
H.div { role: "search" }
[ H.input
{ type: InputSearch
, "aria-label": "Search the docs"
, bindValue: query
, ref: Input.select
, onKeyDown: \event ->
when (KeyboardEvent.key event == "Enter") (get (fst query) >>= submit)
}
, H.p { style: { color: "gray", "font-size": "0.9em" } } "Press Enter"
, H.div { "aria-live": Aria.Polite, innerHTML: "<b>trusted HTML only</b>" } []
]SVG elements live in Solid.DOM.SVG. Use element for a custom tag. Name handlers like onClick or on:customEvent. Attribute names are passed through as written.
icon :: JSX
icon = S.svg { viewBox: "0 0 24 24", width: "24" }
(S.path { d: "M4 12h16", stroke: "currentColor", strokeWidth: "2" } [])widget :: JSX
widget =
element "my-widget" { "label-text": "Hi", onClick: \_ -> pure unit }
[ text "content" ]API: Solid.Component Solid.DOM Solid.DOM.HTML Solid.DOM.SVG Solid.DOM.Aria Solid.JSX
Signals, memos and effects
Component bodies create signals, memos and effects in Setup. Use sample for a one-time read in setup and pass an Accessor for values that should stay reactive. get, set and modify run in Effect, for example in a handler.
stepper :: Component.Component { step :: Int }
stepper = Component.component \props -> do
count /\ setCount <- createSignal 0
label <- createMemo ((\n -> "count: " <> show n) <$> count)
createEffect count \n -> do
log ("count is now " <> show n)
pure (pure unit)
pure $ H.button { onClick: \_ -> modify_ setCount (_ + props.step) } labelAn effect splits into a tracked computation and an untracked apply step that can return a cleanup. Use liftSetup for setup effects such as creating a ref.
API: Solid.Signal Solid.Reactivity Solid.Setup Solid.Lifecycle Solid.Context
Control flow
Control flow creates a view when its branch is shown. Use forEachBy with a stable key such as a record's ID to reuse rows when the array changes.
todoList :: Accessor (Array Todo) -> Accessor (Maybe String) -> JSX
todoList todos error = H.section {}
[ Control.whenElse (Array.null <$> todos)
(H.p {} "Nothing to do")
(H.h2 {} "Todos")
, H.ul {} $ Control.forEachBy _.id todos \todo _ ->
pure (H.li {} (_.title <$> todo))
, Control.showMaybe error \message -> pure (H.p { role: "alert" } message)
]caseOn switches on a data type and rebuilds a branch only when the key changes, here the constructor.
data Page = Home | Profile Int
derive instance Generic Page _
pageView :: Accessor Page -> JSX
pageView page =
Control.caseOn Control.constructorName page \current _ -> pure case current of
Home -> text "Home"
Profile id -> text ("Profile " <> show id)API: Solid.Control
Stores
Stores hold nested state. Updates are pure Update values on typed paths, applied to Solid's draft; reads go through cursors, so each row only tracks the fields it shows.
type Todo = { id :: Int, title :: String, done :: Boolean }
todos :: Component.Component {}
todos = Component.component \_ -> do
state /\ setState <- Store.createStore { todos: [] :: Array Todo }
let
add title = Store.update setState $
Store.atKey @"todos" (Store.push { id: 0, title, done: false })
whereId id = Store.atKey @"todos" <<< Store.eachWhere (\todo -> todo.id == id)
toggle id = Store.update setState $
whereId id (Store.atKey @"done" (Store.modify not))
rows = Store.items (Store.focusKey @"todos" state)
pure $ H.div {}
[ H.button { onClick: \_ -> add "Write docs" } "Add"
, H.ul {} $ Control.forEach rows \row _ -> pure $
H.li
{ onClick: \_ -> Store.snapshot (Store.focusKey @"id" row) >>= toggle }
(Store.value (Store.focusKey @"title" row))
]API: Solid.Store
Async data
createAsync runs an Aff for each value of its input and kills superseded ones. The result is an Async, which may not have loaded, so it has no get: render it, derive from it, or await it with resolve. loading shows a fallback until it's ready, and errored catches failures.
user :: Component.Component { id :: Accessor Int }
user = Component.component \props -> do
found /\ reload <- createAsync (fetchUser <$> props.id)
pure $ Control.loading (H.p {} "Loading…") $
H.div {}
[ H.h2 {} (_.name <$> found)
, H.button { onClick: \_ -> refresh reload } "Reload"
]Use Solid.Action for transactional mutations. Make optimistic writes inside an Action or a router action's onSubmit hook.
API: Solid.Async Solid.Action
Router
route @"/users/:id<int>" gives its component params :: Accessor { id :: Int }. Build links from the same pattern with href. The router handles plain anchors and marks exact pathname and query matches with aria-current="page". A row type defines the search parameters.
app :: Component.Component {}
app = Component.component \_ -> do
router <- Router.createRouter
{ routes:
[ Router.route @"/" \_ -> pure $
H.a { href: href @"/users/:id<int>" { id: 7 } } "User 7"
, Router.route @"/users/:id<int>" \props -> do
search <- useSearch @(tab :: Maybe String)
let
title { id } { tab } =
"User " <> show id <> ", " <> fromMaybe "profile" tab
pure $ H.h1 {} (title <$> props.params <*> searchParams search)
]
}
pure $ Router.routerView router \content -> pure (H.main {} content)Solid.Router.Query caches route data. Solid.Router.Action supports forms, tracked submissions and revalidation. Router 2 deprecates useAction. For programmatic mutations, invoke a server function with call or use Solid.Action.
API: Solid.Router Solid.Router.Path Solid.Router.Search Solid.Router.Query Solid.Router.Action
Server rendering and hydration
Render on the server with renderToString, await server data with renderToStringAsync, or stream with renderToReadableStream. Hydrate the same view on the client.
renderPage :: Aff String
renderPage = do
body <- SSR.renderToStringAsync (Component.element app {}) >>= orThrow
script <- liftEffect SSR.hydrationScript >>= orThrow
pure $ "<!doctype html><html><head>" <> script <> "</head><body>"
<> ("<div id=\"app\">" <> body <> "</div>")
<> "<script src=\"/client.js\"></script></body></html>"
where
orThrow = either throwError pure
main :: Effect Unit
main = hydrateAt "app" (Component.element app {})createAsync loads in the browser by default. Supply ssr: serialized or ssr: withCodec encode decode to createAsyncWith to send the server-loaded value to hydration. Use renderToStringWithHead to collect Solid.Meta tags when assembling the document yourself.
Start mode
Export an app component from module App and run spago build before starting Vite. The wrapper accepts PureScript module names for start.app and start.middleware. A middleware module exports middleware :: MiddlewareFn.
import { defineConfig } from "vite";
import solid from "purs-solid/vite";
export default defineConfig({ plugins: [solid({ start: true, ssr: true })] });The wrapper compiles eligible views to Solid templates. Set compileViews: false to use the runtime renderer for every view. Set start.nodeServer to true to generate a Node server.
Re-export Solid.Start.UseServer from a server module and define its functions with serverFunction. Use Serializable arguments and results.
module App.Api
( module Solid.Start.UseServer
, greet
) where
import Prelude
import Solid.Start.ServerFunction as Server
import Solid.Start.UseServer (useServer)
greet :: Server.ServerFunction String String
greet = Server.serverFunction \name ->
pure ("Hello, " <> name)Invoke a server function in Aff with call. Use queryServer for a cached read or serverAction to wrap a mutation that returns a Reply.
API: Solid.Start.ServerFunction Solid.Start.UseServer Solid.Start.RequestEvent Solid.Start.Response Solid.Start.Middleware
Testing
Solid.Testing mounts views into a DOM (happy-dom works) and waits for Solid to settle. It doesn't depend on a test framework.
spec :: Spec Unit
spec = it "counts clicks" do
mounted <- mount (Component.element counter {})
button <- query "button" mounted
for_ button (liftEffect <<< click)
html mounted >>= (_ `shouldSatisfy` contains (Pattern "<span>1</span>"))
liftEffect mounted.disposeAPI: Solid.Testing