Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

Server-Rendered React Sparkline Example

Vaguely inspired by Easy SVG sparklines, but totally different because that had zero dependencies and this has all the dependencies: react, htm, react-sparklines.

This is the live-generated SVG that this very val generates:

Example SVG Sparkline

![Example SVG Sparkline](https://stevekrouse-sparklineex.web.val.run)

It visualizes the amount of times that it itself has been viewed. The data for this val is kept in @stevekrouse.sparklineExData.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/** @jsxImportSource https://esm.sh/react */
import { blob } from "https://esm.town/v/std/blob?v=12";
import { today } from "https://esm.town/v/stevekrouse/today";
import { renderToString } from "npm:react-dom/server";
import { Sparklines, SparklinesLine } from "npm:react-sparklines";
export const sparklineEx = async (req: Request) => {
let sparklineExData = await blob.getJSON("sparklineExData");
sparklineExData[today()] = (sparklineExData[today()] ?? 0) + 1;
let htmlString = renderToString(
<Sparklines data={Object.values(sparklineExData)} width={100} height={40}>
<SparklinesLine color="blue" />
</Sparklines>,
);
htmlString = htmlString.replace(
"<svg",
"<svg xmlns=\"http://www.w3.org/2000/svg\"",
); // hack to add xmlns to embed in Val Town Readme
blob.setJSON("sparklineExData", sparklineExData);
return new Response(htmlString, {
headers: {
"content-type": "image/svg+xml",
},
});
};
stevekrouse-sparklineex.web.val.run
July 19, 2024