@tooark/react
v1.12.0
Published
Tooark React — typed wrappers for ark-* components for React 18 and 19
Readme
@tooark/react
Typed React wrappers for the Tooark Web Components: camelCase props, custom events as handlers, JSX typings for every ark-* tag. React 18 and 19.
🌍 Languages:
English (this file) ·
Português
📑 Contents
- Overview
- Installation
- Configuration
- Components
- Usage examples
- Dependencies
- Contributing
- Help & Security
- Support
- License
📖 Overview
The @tooark/react package provides:
- one component per element (67 wrappers:
ArkAlert,ArkAvatar,ArkBadge,ArkButton,ArkCalendar,ArkCard, …) with typed props that extend theArk*StyleOptionsfrom@tooark/core; - camelCase props map to attributes; booleans are passed as present/absent; object props (
events,rows,options, andlocaleJsononArkCalendar/ArkDatepicker) are serialized or assigned as properties for you (on the other wrapperslocaleJsonis a JSON string); - custom events become handlers receiving the
CustomEvent(onChange,onClose,onSelect, …) or, on the calendar, datepicker, clock, carousel and scheduler, itsdetail; every props type also takes React's DOM attributes and handlers (id,style,title,tabIndex,aria-*,data-*,onClick,onKeyDown,onFocus, …), typed and forwarded to the element; what the wrapper defines wins over the React prop of the same name (onChangeis the element'sCustomEvent), and adisabledorloadingbutton never firesonClick; - the elements register themselves on first render, browser only, so SSR frameworks are fine: every element from
@tooark/react, only the wrapper's own from@tooark/react/elements(see Configuration); IntrinsicElementstypings for everyark-*tag, for the side packages or when you prefer the raw element;toast,showToast,dismissToastandsetArkLocale,getArkLocale,observeArkLocale(the app-wide default language) re-exported from@tooark/core.
🔧 Installation
pnpm add @tooark/react @tooark/web-components@tooark/react already depends on @tooark/web-components, @tooark/core and @tooark/tokens, but pnpm does not expose transitive dependencies to your app, and the stylesheet import below comes from @tooark/web-components: install it directly. toast is re-exported by @tooark/react.
Peer dependencies: react and react-dom ≥ 18.
⚙️ Configuration
Import the stylesheet once, in main.tsx or your root layout; nothing else to configure (the wrappers register the elements themselves):
import "@tooark/web-components/styles.css";Smaller bundles: @tooark/react/elements. The main entry registers every element on the first wrapper, so a raw ark-* tag next to a wrapper just works, and the bundle carries all of them: about 481 kB minified and before compression, React and @tooark/core not counted. @tooark/react/elements exports the same wrappers and types, and each one registers only its own element and what it creates inside or coordinates (the items of a menu, the input and calendar of a datepicker): about 22 kB for ArkButton, 39 kB for ArkButton, ArkDialog and ArkInput. Import every wrapper from it: one import from @tooark/react anywhere in the app, yours or a dependency's, brings back the registration of every element. A raw ark-* tag you write without its wrapper is then yours to define, with registerTooarkElements from @tooark/web-components.
import { ArkButton, ArkDialog } from "@tooark/react/elements";📦 Components
One wrapper per element, named after it: ark-button → ArkButton, ark-kv-editor → ArkKvEditor, ark-command-palette → ArkCommandPalette + ArkCommandItem. Each exports its props type (ArkButtonProps, …).
- Props: the element's attributes in camelCase (
iconOnly,stepMinutes,localeJson),className, plus the element's JS properties where they matter (events,rows,options,sizes,colors, andvalueFieldonArkKvEditor, which must be a stable function:useCallback).ArkDataViewis generic over your record type (<ArkDataView<User> rows={users} columns={columns} />types the columnrenderandevent.detail.row) and draws a column'srenderas JSX, through portals into the cells: it returns what a component would (elements, your components, text,nullfor nothing) and runs again on every render, socolumnsneeds nouseMemo(the element only redraws its cells when the column data changes);cardRenderdoes the same for a card body.rowIntentandrowIntentLabel(a record's highlight and its text for screen readers) go in as properties when the reference changes: keep them stable withuseCallback. - Events:
on<Event>for the custom events, receiving theCustomEvent(onChangeonArkSelect/ArkKvEditor,onCloseonArkDialog/ArkDrawer,onSelectonArkMenu/ArkCommandPalette, …);onChangeonArkCalendar/ArkDatepicker/ArkClock,onSlideChangeonArkCarouselandonEventClick/onSlotClick/onViewChange/onRangeChangeonArkSchedulerreceive thedetailitself. Native events bubble from the inner control (onInputonArkInput: readevent.target.value). - State: attributes like
openare the source of truth (ArkDialog open={bool}+onClose), so controlled rendering works and the exit still animates.onOpen/onCloseonArkDialog,ArkDrawer,ArkCommandPalette,ArkMenuandArkPopoverfire only for the element's own event, andonCloseonArkTabsonly for its own tabs:ark-openandark-closebubble, and the ones of an overlay inside (anArkMenuin a dialog) do not reach the outer handler.onToggleonArkAccordionfires only for its own sections and onArkAccordionItemonly for itself (an accordion nested in a panel keeps its own).onQueryonArkCommandPaletteandArkComboboxfires only for the element's ownark-query(both elements emit it). The same holds foronResizeonArkSplitPane,onSlideChangeonArkCarousel,onCollapseonArkNav,onChangeonArkStepper,onToggleonArkNavGroupand the handlers ofArkTreeandArkDataView: one of them inside another (a split pane in a panel of another one) does not call the outer handler.onInput/onChangeonArkInputare the native events of the field, and a control of your own inslot="prefix"/slot="suffix"sends its own through the same host: checkevent.targetwhen you put one there. - Ref: every wrapper forwards
refto itsark-*element (React 18 and 19), typed as the element class from@tooark/web-components, so its methods and properties are typed. Object and callback refs both work (including React 19 callback refs that return a cleanup), and the wrapper's own events and properties keep working.
import { ArkButton, ArkDialog } from "@tooark/react";
import React, { useRef } from "react";
export function Shortcuts() {
const dialog = useRef<React.ComponentRef<typeof ArkDialog>>(null); // the <ark-dialog> element
return (
<>
<ArkButton onClick={() => dialog.current?.show()}>Keyboard shortcuts</ArkButton>
<ArkDialog ref={dialog} label="Keyboard shortcuts">
<p>Ctrl+K opens the command palette.</p>
</ArkDialog>
</>
);
}Side packages (subpaths)
@tooark/react/chart (ArkChart), @tooark/react/code (ArkCodeEditor) and @tooark/react/wysiwyg (ArkWysiwygEditor, ArkWysiwygViewer) wrap the side packages without adding them to the main entry: install @tooark/chart, @tooark/code or @tooark/wysiwyg (optional peers) with their own peers. option, value, the code editor's lists and functions (variables, completions, formatter, extensions: keep them stable with useMemo) and the wysiwyg content/uploadFile go in as properties, only when the reference changes; a controlled editor keeps its cursor. Events: onChartClick; onChange, onSubmit, onFormatError on the code editor (event.detail.value); onChange (the Tiptap JSON in event.detail) and onUploadError on the wysiwyg editor. Importing a subpath also types the raw tag's JS properties in JSX (<ark-chart option={…}>, <ark-code-editor value="…" extensions={…}>); the wysiwyg content stays on the wrapper or the ref, since React types content as the <meta> text attribute.
@tooark/react/chart-core is the same ArkChart without the registration, for an app that registers <ark-chart> with the ECharts it assembles from echarts/core (registerTooarkChart(echarts) from @tooark/chart/core, @tooark/chart 1.12+, before the first render): nothing in it imports @tooark/chart as a value, so the whole echarts package stays out of the bundle. On both subpaths table ("sr-only" | "visible") turns on the chart's data table, with its headers in lang and localeJson (@tooark/chart 1.12+).
@tooark/react/diagram (ArkDiagram) does the same for @tooark/diagram (optional peer, no dependency of its own): spec and highlight go in as properties, only when the reference changes, and selected, selectedEdge, interactive, selectableEdges, edgeRouting, noFlow, theme and localeJson as attributes; onSelect and onHover receive the CustomEvent (event.detail.id and event.detail.kind, node or edge), only from the diagram itself. Without selected/selectedEdge the element keeps the user's selection; with them, update your state in onSelect by the kind. The subpath also types the raw <ark-diagram spec={…} highlight={…}> in JSX.
Full attribute reference, theming guide and E2E hooks: https://github.com/Tooark/web-components#readme · live examples with interaction tests: Storybook.
📝 Usage examples
A form with a confirmation dialog and a toast
import { ArkButton, ArkDialog, ArkInput, ArkSelect, ArkToaster, toast } from "@tooark/react";
import { type FormEvent, useState } from "react";
const ROLES = [
{ value: "dev", label: "Developer" },
{ value: "ops", label: "Operations" }
];
export function ProfileForm() {
const [name, setName] = useState("");
const [role, setRole] = useState("dev");
const [confirming, setConfirming] = useState(false);
function submit(event: FormEvent) {
event.preventDefault();
setConfirming(true);
}
function publish() {
setConfirming(false);
toast.success("Profile published", { description: `Welcome, ${name}.` });
}
return (
<form onSubmit={submit}>
<ArkInput label="Name" value={name} required onInput={(e) => setName((e.target as HTMLInputElement).value)} />
<ArkSelect label="Role" options={ROLES} value={role} onChange={(e) => setRole(e.detail.value)} />
<ArkButton type="submit" intent="primary">
Save
</ArkButton>
<ArkDialog label="Publish changes?" open={confirming} onClose={() => setConfirming(false)}>
<p>Your profile will be visible to the whole team.</p>
<div slot="footer">
<ArkButton variant="ghost" onClick={() => setConfirming(false)}>
Cancel
</ArkButton>
<ArkButton intent="primary" onClick={publish}>
Publish
</ArkButton>
</div>
</ArkDialog>
<ArkToaster position="bottom-right" />
</form>
);
}Routing ark-navigate through your router
ark-navigate bubbles from every ark-* link (ArkNavItem, ArkButton, ArkCard and ArkBreadcrumbItem with href), so one listener at the root routes all of them, raw tags included. It only fires for a plain click: a click with a modifier, target="_blank" or download never emits it and stays with the browser, as with your router's own links. Links to another site are left to the browser too.
import { useEffect } from "react";
// Routes the plain clicks of every ark-* link through the app's router.
export function useArkNavigate(go: (path: string) => void): void {
useEffect(() => {
const handler = (event: Event): void => {
if (event.defaultPrevented) return; // already routed by a handler of the app's own
const { href } = (event as CustomEvent<{ href: string | null }>).detail;
if (!href) return; // a nav item without href: route by `event.detail.value` in the nav's own handler
const url = new URL(href, window.location.href);
if (url.origin !== window.location.origin) return; // another site: the browser follows the link
event.preventDefault();
go(url.pathname + url.search + url.hash);
};
document.addEventListener("ark-navigate", handler);
return () => document.removeEventListener("ark-navigate", handler);
}, [go]);
}React Router (react-router 7; react-router-dom on 6), in the root layout, inside the router. The nav's value follows the route, so the current item follows it too.
import { ArkNav, ArkNavItem } from "@tooark/react";
import { Outlet, useLocation, useNavigate } from "react-router";
export function Layout() {
const navigate = useNavigate();
useArkNavigate((path) => navigate(path));
const { pathname } = useLocation();
return (
<>
<ArkNav value={pathname}>
<ArkNavItem href="/courses">Courses</ArkNavItem>
<ArkNavItem href="/settings">Settings</ArkNavItem>
</ArkNav>
<Outlet />
</>
);
}TanStack Router takes the path already built in href:
import { useLocation, useNavigate } from "@tanstack/react-router";
const navigate = useNavigate();
useArkNavigate((path) => navigate({ href: path }));
const pathname = useLocation({ select: (location) => location.pathname });With a base path (basename, basepath, createWebHistory("/app/"), <base href>), the href in the page includes it, and the router expects the path without it: strip it before routing.
A raw element from a side package
import { registerTooarkChart } from "@tooark/chart";
import { useEffect, useRef } from "react";
export function Sales({ option }: { option: object }) {
const ref = useRef<HTMLElement & { option: object }>(null);
useEffect(() => {
registerTooarkChart();
if (ref.current) ref.current.option = option; // JS property, not an attribute
}, [option]);
return <ark-chart ref={ref} height="320px" />; // typed by @tooark/react's IntrinsicElements
}📋 Dependencies
Installed automatically unless marked as peer; peer dependencies are yours to install (the ranges are what the package declares).
| Package | Version | Description |
| -------------------------------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------- |
| @tooark/core | ^1.12.0 | Types, i18n, toast/announce services, motion and overlay helpers |
| @tooark/web-components | ^1.12.0 | The ark-* Custom Elements and their stylesheet |
| react | >=18 (peer) | React 18 or 19 |
| react-dom | >=18 (peer) | React DOM renderer |
| @tooark/chart | >=1.0.0 (optional peer) | ark-chart, for the /chart and /chart-core subpaths |
| @tooark/code | >=1.6.0 (optional peer) | ark-code-editor, for the /code subpath |
| -------------------------------------------------------------------------------- | ------------------------ | ---------------------------------------------------------------- |
| @tooark/diagram | >=1.12.0 (optional peer) | ark-diagram, for the /diagram subpath |
| @tooark/wysiwyg | >=1.0.0 (optional peer) | ark-wysiwyg-*, for the /wysiwyg subpath |
🪪 Contributing
Contributions are welcome! Open issues and pull requests in the Tooark/web-components repository; CONTRIBUTING.md covers the workflow, the commit convention and the checklist. @tooark/react is released in lockstep with every other @tooark/* package.
🆘 Help & Security
- ❓ Questions, bugs, feature ideas — see SUPPORT.md for the right channel
- 🔒 Security vulnerabilities — do not open a public issue; follow SECURITY.md
💖 Support
If this project helps your workflow, consider supporting its development:
Every contribution helps keep the project maintained and improving. Thank you! 🙏
📄 License
This project is licensed under the Apache License 2.0. See the LICENSE file for details.
