# Tutorial
Build a coffee-ordering screen in six steps: a menu from your server, an order kept on the phone, sent back, and remembered for next time.
Each step shows `server/Home.tsx`, with what changed marked.
The steps use the React Native template, the Quick start's default. On a web
template, `--template react` or `--template solid-js`, the same steps work
with the browser's elements:
- **Elements:** `<$View>`, `<$ScrollView>` and `<$Text>` become `
`,
`` and ``, written without `$`: the browser draws them.
- **Taps:** `<$Pressable onPress={…}>` becomes ``.
- **Styles:** `$StyleSheet.create({…})` becomes a plain style object:
`{ fontSize: 18 }` for React, `{ "font-size": "18px" }` for Solid.
- **State, in Solid:** `$createSignal` and `$createStore`, imported from
`solid-js` and `solid-js/store` with `with { backtick: "client" }`, replace
`$useState`. A Solid component runs once, so a value computed from state is
a function you call, `total()`, or it never updates. Lists use `<$For>`.
- **Reloading:** refresh the page.
Start from the project the [Quick start](/docs/) creates, with the app running,
and clear the welcome screen:
```sh
npm run reset-project
```
It also rewrites `server/Home.test.tsx` to test the blank screen. Delete that
file: the last step writes one for the screen you're about to build.
## 1. Show the menu
The menu is data your server reads. Here it's a file; yours could come from a
database or an API. Create `server/menu.ts`:
```ts title="server/menu.ts"
// The menu. Yours could come from a database or an API: anything your server
// can read.
export type Coffee = { id: string; name: string; price: number };
export async function getMenu(): Promise {
return [
{ id: "flat-white", name: "Flat white", price: 4.5 },
{ id: "cortado", name: "Cortado", price: 4 },
{ id: "cold-brew", name: "Cold brew", price: 5 },
];
}
```
Then replace `server/Home.tsx`:
```tsx title="server/Home.tsx"
import { cs } from "@backtickjs/core";
import {
ScrollView,
StatusBar,
StyleSheet,
Text,
View,
} from "react-native" with { backtick: "client" };
import { getMenu } from "./menu.js";
export async function Home() {
const menu = await getMenu();
return cs`{
const styles = $StyleSheet.create({
screen: {
padding: 24,
paddingTop: ($StatusBar.currentHeight ?? 0) + 24,
gap: 16,
},
title: { fontSize: 32, fontWeight: "bold" },
row: { flexDirection: "row", justifyContent: "space-between" },
name: { fontSize: 18 },
price: { fontSize: 18, color: "#666" },
});
return (
<$ScrollView
contentInsetAdjustmentBehavior="automatic"
contentContainerStyle={styles.screen}
>
<$Text style={styles.title}>Menu$Text>
{$menu.map((coffee) => (
<$View key={coffee.id} style={styles.row}>
<$Text style={styles.name}>{coffee.name}$Text>
<$Text style={styles.price}>
{coffee.price.toLocaleString("en-US", {
style: "currency",
currency: "USD",
})}
$Text>
$View>
))}
$ScrollView>
);
}`;
}
```
Save, and the menu appears. `Home` awaited it on your server, and `$menu`
wrote it into the screen, typed as `getMenu` returns it. The styles are made
in the script, with `$StyleSheet.create`: they're code that runs on the
phone, like the JSX.
## 2. Add a client component
Each coffee gets an "Add" button that counts its taps. A tap is handled on the
phone, so the button is a client component: a script that takes props, with
state of its own.
```diff title="server/Home.tsx"
@@ -1,5 +1,7 @@
import { cs } from "@backtickjs/core";
+import { useState } from "react" with { backtick: "client" };
import {
+ Pressable,
ScrollView,
StatusBar,
StyleSheet,
@@ -8,6 +10,18 @@
} from "react-native" with { backtick: "client" };
import { getMenu } from "./menu.js";
+// A client component: it runs on the phone, with state of its own.
+const AddButton = cs`() => {
+ const [count, setCount] = $useState(0);
+ return (
+ <$Pressable onPress={() => setCount(count + 1)}>
+ <$Text style={{ fontSize: 18, color: "#0a7ea4" }}>
+ {count === 0 ? "Add" : "Added " + count}
+ $Text>
+ $Pressable>
+ );
+}`;
+
export async function Home() {
const menu = await getMenu();
@@ -39,6 +53,7 @@
currency: "USD",
})}
$Text>
+ <$AddButton />
$View>
))}
$ScrollView>
```
Tap "Add" a few times. Each button keeps its own count: `AddButton` is a
client component, like `Counter` in the quick start, and each tag is its own
instance.
## 3. Share the order across the screen
Counts kept in each button can't add up to a total. The order belongs one level
up, in a client component that holds every count and draws the rows.
```diff title="server/Home.tsx"
@@ -8,55 +8,85 @@
Text,
View,
} from "react-native" with { backtick: "client" };
-import { getMenu } from "./menu.js";
+import { type Coffee, getMenu } from "./menu.js";
-// A client component: it runs on the phone, with state of its own.
-const AddButton = cs`() => {
- const [count, setCount] = $useState(0);
- return (
- <$Pressable onPress={() => setCount(count + 1)}>
- <$Text style={{ fontSize: 18, color: "#0a7ea4" }}>
- {count === 0 ? "Add" : "Added " + count}
+// The screen's styles: a script too, one the components below share.
+const styles = cs`$StyleSheet.create({
+ screen: {
+ padding: 24,
+ paddingTop: ($StatusBar.currentHeight ?? 0) + 24,
+ gap: 16,
+ },
+ title: { fontSize: 32, fontWeight: "bold" },
+ row: { flexDirection: "row", justifyContent: "space-between" },
+ name: { fontSize: 18 },
+ add: { fontSize: 18, color: "#0a7ea4" },
+ total: { fontSize: 18, fontWeight: "600", marginTop: 8 },
+})`;
+
+// A client function, which any script can call.
+const formatPrice = cs`(price: number) =>
+ price.toLocaleString("en-US", { style: "currency", currency: "USD" })`;
+
+// One coffee, its price until it's in the order, then how many are.
+const CoffeeRow = cs`(props: {
+ coffee: Coffee;
+ count: number;
+ onAdd: () => void;
+}) => (
+ <$View style={$styles.row}>
+ <$Text style={$styles.name}>{props.coffee.name}$Text>
+ <$Pressable onPress={props.onAdd}>
+ <$Text style={$styles.add}>
+ {props.count === 0
+ ? $formatPrice(props.coffee.price)
+ : props.count + " ×"}
$Text>
$Pressable>
+ $View>
+)`;
+
+// The order: how many of each coffee, kept on the phone.
+const Order = cs`(props: { menu: Coffee[] }) => {
+ const [counts, setCounts] = $useState>({});
+ const add = (id: string) =>
+ setCounts({ ...counts, [id]: (counts[id] ?? 0) + 1 });
+
+ const items = Object.values(counts).reduce((sum, n) => sum + n, 0);
+ const total = props.menu.reduce(
+ (sum, coffee) => sum + (counts[coffee.id] ?? 0) * coffee.price,
+ 0,
);
+
+ return (
+ <$View>
+ {props.menu.map((coffee) => (
+ <$CoffeeRow
+ key={coffee.id}
+ coffee={coffee}
+ count={counts[coffee.id] ?? 0}
+ onAdd={() => add(coffee.id)}
+ />
+ ))}
+ <$Text style={$styles.total}>
+ {items === 0
+ ? "Tap a price to add it."
+ : items + " in your order · " + $formatPrice(total)}
+ $Text>
+ $View>
+ );
}`;
export async function Home() {
const menu = await getMenu();
- return cs`{
- const styles = $StyleSheet.create({
- screen: {
- padding: 24,
- paddingTop: ($StatusBar.currentHeight ?? 0) + 24,
- gap: 16,
- },
- title: { fontSize: 32, fontWeight: "bold" },
- row: { flexDirection: "row", justifyContent: "space-between" },
- name: { fontSize: 18 },
- price: { fontSize: 18, color: "#666" },
- });
-
- return (
- <$ScrollView
- contentInsetAdjustmentBehavior="automatic"
- contentContainerStyle={styles.screen}
- >
- <$Text style={styles.title}>Menu$Text>
- {$menu.map((coffee) => (
- <$View key={coffee.id} style={styles.row}>
- <$Text style={styles.name}>{coffee.name}$Text>
- <$Text style={styles.price}>
- {coffee.price.toLocaleString("en-US", {
- style: "currency",
- currency: "USD",
- })}
- $Text>
- <$AddButton />
- $View>
- ))}
- $ScrollView>
- );
- }`;
+ return cs`(
+ <$ScrollView
+ contentInsetAdjustmentBehavior="automatic"
+ contentContainerStyle={$styles.screen}
+ >
+ <$Text style={$styles.title}>Menu$Text>
+ <$Order menu={$menu} />
+ $ScrollView>
+ )`;
}
```
Tap a price to add a coffee; the total updates below.
- **`styles` and `formatPrice` are scripts too,** a value and a function rather
than components. Each component splices the ones it uses, and the bundle
carries each script once.
- **`Order` holds the state; `CoffeeRow` gets it as props,** a count and an
`onAdd` callback, as in any React app. Inside client code, props can be
anything: functions included.
## 4. Send the order to your server
The order is placed with a `fetch` from the phone. First, the server needs
somewhere to keep orders. Create `server/orders.ts`:
```ts title="server/orders.ts"
// Orders, kept in memory while the server runs. Yours would go to a database.
export type Counts = Record;
let last: Counts | null = null;
export async function saveOrder(counts: Counts): Promise {
last = counts;
}
export async function lastOrder(): Promise {
return last;
}
```
Then add a route for them to `server/index.tsx`, and pass `Home` the address
the app reached your server at:
```diff title="server/index.tsx"
@@ -4,6 +4,7 @@
import { Hono } from "hono";
import { cors } from "hono/cors";
import { Home } from "./Home.js";
+import { saveOrder } from "./orders.js";
const app = new Hono();
@@ -21,8 +22,16 @@
// Your app's screens: `render` bundles each one for the app. A path can take
// parameters, `/stories/:id`, read with `context.req.param("id")`.
-app.get("/", (context) => render(context.req.raw, ));
+// with where the app reached this server, for the screen to send its order to
+app.get("/", (context) =>
+ render(context.req.raw, ),
+);
+app.post("/orders", async (context) => {
+ await saveOrder(await context.req.json());
+ return context.body(null);
+});
+
// What a route throws: logged, and answered as a 500.
app.onError((error, context) => {
console.error(error);
```
Now the screen can send its order there:
```diff title="server/Home.tsx"
@@ -22,6 +22,14 @@
name: { fontSize: 18 },
add: { fontSize: 18, color: "#0a7ea4" },
total: { fontSize: 18, fontWeight: "600", marginTop: 8 },
+ button: {
+ marginTop: 16,
+ padding: 14,
+ borderRadius: 12,
+ alignItems: "center",
+ backgroundColor: "#0a7ea4",
+ },
+ buttonText: { fontSize: 18, fontWeight: "600", color: "#fff" },
})`;
// A client function, which any script can call.
@@ -46,11 +54,19 @@
$View>
)`;
-// The order: how many of each coffee, kept on the phone.
-const Order = cs`(props: { menu: Coffee[] }) => {
+// The order: how many of each coffee, kept on the phone until it's placed.
+const Order = cs`(props: { menu: Coffee[]; ordersUrl: string }) => {
const [counts, setCounts] = $useState>({});
+ const [placed, setPlaced] = $useState(false);
const add = (id: string) =>
setCounts({ ...counts, [id]: (counts[id] ?? 0) + 1 });
+ const place = async () => {
+ await fetch(props.ordersUrl, {
+ method: "POST",
+ body: JSON.stringify(counts),
+ });
+ setPlaced(true);
+ };
const items = Object.values(counts).reduce((sum, n) => sum + n, 0);
const total = props.menu.reduce(
@@ -73,12 +89,20 @@
? "Tap a price to add it."
: items + " in your order · " + $formatPrice(total)}
$Text>
+ {items > 0 && (
+ <$Pressable style={$styles.button} onPress={place} disabled={placed}>
+ <$Text style={$styles.buttonText}>
+ {placed ? "Ordered ✓" : "Place order"}
+ $Text>
+ $Pressable>
+ )}
$View>
);
}`;
-export async function Home() {
+export async function Home({ origin }: { origin: string }) {
const menu = await getMenu();
+ const ordersUrl = origin + "/orders";
return cs`(
<$ScrollView
@@ -86,7 +110,7 @@
contentContainerStyle={$styles.screen}
>
<$Text style={$styles.title}>Menu$Text>
- <$Order menu={$menu} />
+ <$Order menu={$menu} ordersUrl={$ordersUrl} />
$ScrollView>
)`;
}
```
On a web template, `server/index.tsx` draws the page with `toHtml`: pass
`origin` to `` there, and add the same `/orders` route. It needs no
`cors`, since the page and its server share an address.
Add a coffee, then tap "Place order".
- **`Home` takes props now.** The server reads them from the request, here the
`origin`, and `Home` turns them into the screen.
- **The `/orders` route is an ordinary handler:** the screen talks to your
server like any app would, with a `fetch` from the phone.
## 5. Make it personal
The server knows your last order, so the screen can start with it.
```diff title="server/Home.tsx"
@@ -9,6 +9,7 @@
View,
} from "react-native" with { backtick: "client" };
import { type Coffee, getMenu } from "./menu.js";
+import { type Counts, lastOrder } from "./orders.js";
// The screen's styles: a script too, one the components below share.
const styles = cs`$StyleSheet.create({
@@ -18,6 +19,7 @@
gap: 16,
},
title: { fontSize: 32, fontWeight: "bold" },
+ usual: { fontSize: 16, color: "#666" },
row: { flexDirection: "row", justifyContent: "space-between" },
name: { fontSize: 18 },
add: { fontSize: 18, color: "#0a7ea4" },
@@ -55,8 +57,13 @@
)`;
// The order: how many of each coffee, kept on the phone until it's placed.
-const Order = cs`(props: { menu: Coffee[]; ordersUrl: string }) => {
- const [counts, setCounts] = $useState>({});
+// It starts as the order the server gives it.
+const Order = cs`(props: {
+ menu: Coffee[];
+ ordersUrl: string;
+ initialCounts: Counts;
+}) => {
+ const [counts, setCounts] = $useState(props.initialCounts);
const [placed, setPlaced] = $useState(false);
const add = (id: string) =>
setCounts({ ...counts, [id]: (counts[id] ?? 0) + 1 });
@@ -100,9 +107,20 @@
);
}`;
+// A server component, drawn inside the script below: your last order, in
+// words.
+async function Usual({ counts, menu }: { counts: Counts; menu: Coffee[] }) {
+ const summary = menu
+ .filter((coffee) => counts[coffee.id])
+ .map((coffee) => `${counts[coffee.id]} × ${coffee.name}`)
+ .join(", ");
+ return cs`<$Text style={$styles.usual}>Your usual: {$summary}$Text>`;
+}
+
export async function Home({ origin }: { origin: string }) {
const menu = await getMenu();
const ordersUrl = origin + "/orders";
+ const usual = await lastOrder();
return cs`(
<$ScrollView
@@ -110,7 +128,12 @@
contentContainerStyle={$styles.screen}
>
<$Text style={$styles.title}>Menu$Text>
- <$Order menu={$menu} ordersUrl={$ordersUrl} />
+ {${usual === null ? null : }}
+ <$Order
+ menu={$menu}
+ ordersUrl={$ordersUrl}
+ initialCounts={${usual ?? {}}}
+ />
$ScrollView>
)`;
}
```
Your server keeps orders in memory, and it restarted when you saved, so place
an order now, then reload the app: press `r` in the terminal running it.
"Your usual" appears, and the order starts with it.
- **`Usual` is a server component drawn inside a script,** with a braced
splice: `{${ }}`. It runs on your server,
and the phone gets only what it returns.
- **`${usual ?? {}}` is a splice of an expression,** for when a name isn't
enough. It's the order's starting state.
## 6. Test it
A test draws the screen as your app does, taps it, and checks what it shows.
Create `server/Home.test.tsx`:
```tsx title="server/Home.test.tsx"
import assert from "node:assert/strict";
import { afterEach, beforeEach, it } from "node:test";
import { render, screen } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
import { Home } from "./Home.js";
import { saveOrder } from "./orders.js";
import { drawScreen } from "./test/drawScreen.js";
// The phone's `fetch`, answered here rather than by your server.
const sent: string[] = [];
const realFetch = globalThis.fetch;
beforeEach(() => {
sent.length = 0;
globalThis.fetch = async (_url, init) => {
sent.push(String(init?.body));
return new Response();
};
});
afterEach(() => {
globalThis.fetch = realFetch;
});
it("totals the order, and places it", async () => {
render(await drawScreen( ));
await userEvent.click(screen.getByText("$4.50"));
await userEvent.click(screen.getByText("$4.00"));
assert.ok(screen.getByText("2 in your order · $8.50"));
await userEvent.click(screen.getByText("Place order"));
assert.ok(await screen.findByText("Ordered ✓"));
assert.deepEqual(JSON.parse(sent[0]!), { "flat-white": 1, cortado: 1 });
});
it("starts from the usual", async () => {
await saveOrder({ "flat-white": 2 });
render(await drawScreen( ));
assert.ok(screen.getByText("Your usual: 2 × Flat white"));
assert.ok(screen.getByText("2 in your order · $9.00"));
});
```
`npm test` runs it. The web templates have no tests yet, so this step needs
the React Native template. The phone's `fetch` is answered in the test, so placing an
order doesn't need your server; the usual does, through `saveOrder`.
[Testing screens](/docs/testing/) explains `drawScreen`, and what a test
doesn't cover.
## What you learned
| You wrote | It's a | It runs on |
| -------------------------------------------- | --------------------------------------- | -------------------- |
| `async function Home()` | Server component | Your server |
| `` cs`…` `` | Client script | The phone |
| `$menu`, `${usual ?? {}}` | Splice: a server value, written as data | Crosses to the phone |
| `` cs`(props) => …` ``, used as `<$Order />` | Client component | The phone |
| `{${ }}` | A server component inside a script | Your server |
Everything you changed lives in `server/`. Deploy your server, and every user
has the new screen the next time they open it, without an app release. And
the server builds each screen per request, so `lastOrder` could read the
user's account, A/B group or location.
Next, **[Thinking in Backtick](/docs/thinking-in-backtick/)** explains the
model behind these steps.