Styling
Style Xote apps with plain CSS, and let classes, inline styles and data attributes follow your signals.
Xote has no styling system of its own: you write CSS and point elements at it with class, style and data attributes. What Xote adds is that any of those can follow a signal, so the page restyles itself when state changes.
Add a stylesheet
The simplest setup is a plain CSS file linked from index.html. Vite processes it in development and bundles it for production:
1<link rel="stylesheet" href="/src/styles.css" />
You can also import CSS from a ReScript module. ReScript has no CSS import syntax, so use a raw top-level import; Vite picks it up like any other import:
1// App.res2%%raw(`import "./App.css"`)
This keeps a component's styles next to its code, which is handy once the app grows.
Use static classes
class takes a string, exactly like HTML's class attribute:
1@xote.component2let make = () => <section class="card card-elevated"> {"Static classes"} </section>
Switch classes with state
Read a signal in the class expression. Under @xote.component, that attribute becomes its own reactive binding, so only the attribute updates when the signal changes:
1let isOpen = Signal.make(false)23@xote.component4let make = () =>5 <div class={Signal.get(isOpen) ? "panel panel-open" : "panel"}>6 <button onClick={_ => Signal.update(isOpen, v => !v)}> {"Toggle"} </button>7 </div>
When several classes toggle independently, a small helper keeps the markup readable. Signal reads inside its arguments are still tracked, because they appear in the attribute:
1let classNames = (pairs: array<(string, bool)>) =>2 pairs->Array.filterMap(((name, on)) => on ? Some(name) : None)->Array.join(" ")34@xote.component5let make = () =>6 <li7 class={classNames([8 ("option", true),9 ("option-selected", Signal.get(selected)),10 ("option-disabled", Signal.get(disabled)),11 ])}>12 {"Item"}13 </li>
Set inline styles
style takes a CSS declaration string, like the HTML attribute (not an object). Inline styles are best for values that really are dynamic, such as a width or a position:
1let progress = Signal.make(40)23@xote.component4let make = () =>5 <div class="bar">6 <div class="bar-fill" style={`width: ${Int.toString(Signal.get(progress))}%`} />7 </div>
For everything else, prefer a class: it keeps the look in your CSS, where hover states and media queries live.
Style with data attributes
Data attributes are a good fit for state that CSS should react to, like a status or a variant. Set them through the attrs prop. A value there can be a plain string, a signal, or a () => … function:
1let status = Signal.make("idle")23@xote.component4let make = () =>5 <span class="badge" attrs=[("data-status", () => Signal.get(status))]>6 {Signal.get(status)}7 </span>
1.badge[data-status="saving"] { opacity: 0.6; }2.badge[data-status="error"] { color: crimson; }
attrs is not rewritten by @xote.component. Pass the signal itself or a function, as above; a bare Signal.get(status) there is read once and never updates.
Theme with a signal
Keep the theme in a signal and expose it to CSS as a data attribute. For a section of the page, put it on that element:
1let theme = Signal.make("dark")23@xote.component4let make = () =>5 <div class="app" attrs=[("data-theme", theme)]>6 <button onClick={_ => Signal.update(theme, t => t == "dark" ? "light" : "dark")}>7 {"Switch theme"}8 </button>9 </div>
To theme the whole document, including <body>, set the attribute on <html> from an effect. The effect re-runs whenever the theme changes. It touches document, so if your app also renders on the server, only start it in the browser:
1@val @scope("document") external documentElement: Dom.element = "documentElement"2@send external setAttribute: (Dom.element, string, string) => unit = "setAttribute"34if SSRContext.isClient {5 Effect.run(() => {6 documentElement->setAttribute("data-theme", Signal.get(theme))7 None8 })9}
Then define your colours as CSS custom properties per theme:
1:root { --bg: #0b0d0c; --text: #f2f4ee; }2[data-theme="light"] { --bg: #ffffff; --text: #0b0d0c; }3body { background: var(--bg); color: var(--text); }
Switching the theme now changes one attribute, and the browser restyles everything that uses the variables.
Common mistakes
- Passing an object to
style.styleis a string of declarations, as in HTML:"width: 40%; color: red". - Expecting
attrsto trackSignal.get.attrsentries are read once unless the value is a signal or a function. - Rebuilding markup to change a look. Swapping whole elements to change colours is slower and loses focus. Toggle a class or data attribute instead.
- Hiding a read in a
let.let cls = Signal.get(isOpen) ? "a" : "b"in the component body is read once. Put the expression in the attribute, where the annotation can track it. See Thinking in signals.
Summary
Xote has no styling system: elements get CSS through class, style (a CSS declaration string) and attributes (attrs, or the data object). Each of these can be static or reactive. Reactive styling is attribute-level: when a signal changes, only that attribute is rewritten; elements are not rebuilt. The one rule that matters most: reactive values in class/style come from a signal read in the attribute expression (PPX) or a signal/thunk value, while attrs and data entries are never rewritten by the PPX and MUST be given a signal or a thunk to stay live.
Availability
| Item | Import / entry | First stable | Changed in 7.2.0 | Needs the PPX |
|---|---|---|---|---|
class, style, id, title, hidden props | xote (JSX) | 7.0.0 | — | No |
Inline Signal.get in class/style | xote | 7.1.0 | — | Yes (@xote.component) |
attrs escape hatch; removing an attribute with None | xote | 7.1.0 | — | No |
data object prop (left as written by the PPX) | xote | 7.1.0 | — | No |
View.onMount (DOM work after mount) | xote | 7.2.0 (new) | — | No |
SSRContext.isClient / onClient | xote, xote/ssr-context | stable (all 7.x) | — | No |
Rules
classtakes one space-separated string. Accepted shapes:string,Signal.t<string>,unit => string,MaybeSignal.t<string>.classNameis not a prop (compile error).- Under
@xote.component, aclassorstyleexpression on an intrinsic element that reads a signal becomes a reactive leaf: only that attribute updates when the signal changes. styletakes a CSS declaration string ("width: 40%; color: red"), with the same accepted shapes asclass. The prop's type is generic, so a ReScript object or record compiles but rendersstyle="[object Object]".attrsisarray<(string, 'a)>: every entry has the same value type. Values may bestring,Signal.t<string>,unit => string,MaybeSignal.t<string>,option<string>(Noneremoves the attribute), or aView.attrValuebuilt withView.attr/View.signalAttr/View.computedAttr. To mix static and reactive entries in one array, build every entry withView.attr/View.signalAttr/View.computedAttr.- The PPX leaves
attrs,dataand event handlers exactly as written.attrs=[("data-state", Signal.get(state))]is read once and never updates; use("data-state", state)or("data-state", () => Signal.get(state)). - An
attrsentry is applied after the typed props; for the same attribute name theattrsentry wins, and the last entry for a key wins. - A thunk or signal whose value is
None(ornull/undefined) removes the attribute; returningSome("")sets it present and empty. Use this for presence-based selectors such as[data-open]. - The
dataprop is typedObj.t: an object whose keys becomedata-<key>attributes, each value static, a signal, or a thunk. Building it requiresObj.magic; preferattrswith explicitdata-*names. - Boolean attributes (
hidden,disabled, …) are present whentrueand removed whenfalse. - CSS files are bundler inputs. Link them from
index.html, or import them from a ReScript module with%%raw(import "./File.css"); the path is resolved relative to the compiled.res.mjs(next to the.reswhen"in-source": true). - Code that touches
documentorwindow(for example settingdata-themeon<html>) MUST NOT run during server rendering or prerendering. Guard it withSSRContext.isClient/SSRContext.onClient, or run it inView.onMount. - Restyling SHOULD toggle classes or data attributes, not swap elements: swapping rebuilds DOM and loses focus, selection and transitions.
API
| Name | Signature | Behaviour |
|---|---|---|
class prop | string | Signal.t<string> | unit => string | MaybeSignal.t<string> | Sets class. |
style prop | same as class (string content) | Sets the style attribute. |
hidden prop | bool | Signal.t<bool> | unit => bool | Presence attribute. |
attrs prop | array<(string, 'a)> | Any attribute; one value type per array. |
data prop | Obj.t | Object of data-* values. |
View.attr | (string, string) => (string, attrValue) | Static entry for attrs. |
View.signalAttr | (string, Signal.t<string>) => (string, attrValue) | Signal entry. |
View.computedAttr | (string, unit => string) => (string, attrValue) | Derived entry. |
SSRContext.isClient | bool | true when document existed when Xote loaded. |
SSRContext.onClient | (unit => 'a) => option<'a> | Runs only in the browser. |
Patterns
Toggle a class — Use when: a component has visual states.
1let isOpen = Signal.make(false)23@xote.component4let make = () =>5 <div class={Signal.get(isOpen) ? "panel panel-open" : "panel"}>6 <button onClick={_ => Signal.update(isOpen, v => !v)}> {"Toggle"} </button>7 </div>
Several independent classes — Use when: more than one flag affects the class list. The helper call sits in the attribute, so its signal reads are tracked.
1let classNames = (pairs: array<(string, bool)>) =>2 pairs->Array.filterMap(((name, on)) => on ? Some(name) : None)->Array.join(" ")34@xote.component5let make = () =>6 <li7 class={classNames([8 ("option", true),9 ("option-selected", Signal.get(selected)),10 ("option-disabled", Signal.get(disabled)),11 ])}>12 {"Item"}13 </li>
Dynamic inline style — Use when: a value is continuous (width, position, progress).
1let progress = Signal.make(40)23@xote.component4let make = () =>5 <div class="bar">6 <div class="bar-fill" style={`width: ${Int.toString(Signal.get(progress))}%`} />7 </div>
Data attributes for CSS state — Use when: CSS should branch on an enumerated state.
1let status = Signal.make("idle")23@xote.component4let make = () =>5 <span class="badge" attrs=[("data-status", status)]> {Signal.get(status)} </span>
1.badge[data-status="saving"] { opacity: 0.6; }2.badge[data-status="error"] { color: crimson; }
Presence attribute — Use when: a selector tests for presence ([data-open]).
1@xote.component2let make = () =>3 <div attrs=[("data-open", () => Signal.get(isOpen) ? Some("") : None)] />
Mixed static and reactive attributes — Use when: one attrs array needs both.
1@xote.component2let make = () =>3 <div attrs=[View.attr("role", "status"), View.signalAttr("data-theme", theme)] />
App-wide theme — Use when: the theme applies to <html>/<body>. Guard for the server.
1let theme = Signal.make("dark")23@val @scope("document") external documentElement: Dom.element = "documentElement"4@send external setAttribute: (Dom.element, string, string) => unit = "setAttribute"56if SSRContext.isClient {7 Effect.run(() => {8 documentElement->setAttribute("data-theme", Signal.get(theme))9 None10 })11}
1:root { --bg: #0b0d0c; --text: #f2f4ee; }2[data-theme="light"] { --bg: #ffffff; --text: #0b0d0c; }3body { background: var(--bg); color: var(--text); }
Component-scoped stylesheet — Use when: styles live next to a component.
1// Card.res2%%raw(`import "./Card.css"`)34@xote.component5let make = (~children: View.node) => <section class="card"> {children} </section>
Anti-patterns
-
Reading a signal in
attrsdirectly. Wrong:attrs=[("data-status", Signal.get(status))]. Symptom: the attribute keeps its first value forever. Right:attrs=[("data-status", status)]or("data-status", () => Signal.get(status)). Why: the PPX does not rewriteattrs; the expression is evaluated once. -
Object
style. Wrong:style={{"color": "red"}}. Symptom: compiles; the DOM getsstyle="[object Object]"; no styling applies. Right:style="color: red"or a template string. -
Mixing value types in
attrs. Wrong:attrs=[("data-a", "x"), ("data-theme", theme)]. Symptom: compile errorThis has type: Signal.t<string> But it's expected to have type: string. Right:attrs=[View.attr("data-a", "x"), View.signalAttr("data-theme", theme)]. -
Computing the class in the component body. Wrong:
let cls = Signal.get(isOpen) ? "a" : "b"then<div class=cls />. Symptom: the class never changes. Right: put the expression in the attribute. Why: the component body runs once, untracked. -
Touching
documentat module level. Wrong: an unguarded module-levelEffect.runthat callsdocumentElement->setAttribute(…). Symptom: prerendering or server rendering crashes with "document is not defined". Right: guard withif SSRContext.isClient { … }, or do it inView.onMount.
Edge cases
classgiven an array compiles (the prop is generic) and renders the array joined with commas. Always join to a space-separated string.SSRContext.isClientis evaluated once, when Xote's modules load (typeof document !== 'undefined'). In a test runner that installs jsdom after importing modules, it isfalse; see the Testing guide.- A signal passed directly (
class={theme}) and a thunk (class={() => …}) both create a reactive leaf without the PPX. - SVG presentation attributes (
fill,stroke,strokeWidth,opacity,transform, …) are typed props with the same accepted shapes asclass. - Prefer CSS custom properties for theme values; a single attribute change restyles every consumer without touching many elements.
SSR and hydration
class,style,attrsanddatarender into the HTML with their values at render time; hydration attaches the reactive leaves to the existing elements, so later signal changes update those attributes in place.- A theme stored only in the browser (e.g.
localStorage) cannot be known on the server: the first paint uses the server default. Set thedata-themeattribute with an inline script in the HTML<head>before the stylesheet loads to avoid a flash. %%rawCSS imports are handled by Vite in both client and SSR builds.
Verify
- Mount in jsdom and read
element.className,element.getAttribute("style"),element.getAttribute("data-…")afterSignal.set; Zekr hasDom.Assert.toHaveClassandDom.Assert.toHaveAttribute. SSR.renderToString(() => <Comp />)shows the initial attributes as HTML.- Compile error "The field className does not belong to type XoteJSX.Elements.props": use
class.
Related
/docs/learn/rendering— attribute rules in general./docs/guides/forms—value/checked/disabledproperties./docs/learn/lifecycle—View.onMountfor DOM work./docs/guides/deploying— keeping browser-only code out of the server./docs/api/view—View.attr,View.signalAttr,View.computedAttr.