Build TagoIO Custom Widgets with React. This SDK gives you a set of hooks and a Provider component so you can read device data, send data, and access platform resources using familiar React patterns.
If you're looking for the plain JavaScript version, see @tago-io/custom-widget.
npm install @tago-io/custom-widget-react react react-domWrap your app in <TagoIOProvider>, then use hooks to access data:
import { TagoIOProvider, useWidget, useRealtimeData } from "@tago-io/custom-widget-react";
function App() {
return (
<TagoIOProvider>
<Dashboard />
</TagoIOProvider>
);
}
function Dashboard() {
const { widget, isLoading } = useWidget();
const { records } = useRealtimeData();
if (isLoading) return <p>Loading...</p>;
return (
<div>
<h1>{widget?.label}</h1>
<ul>
{records.map((r) => (
<li key={r.id}>
{r.variable}: {r.value}
</li>
))}
</ul>
</div>
);
}<TagoIOProvider
realtimeStrategy="merge" // "replace" | "append" | "merge" (default: "merge")
realtimeMaxRecords={1000} // "append" only: how many realtime blocks to keep, not records (default: 1000)
allowedOrigins={["https://admin.tago.io"]} // optional: drops messages from every other origin
dictionary={MyDictionary} // optional: a class whose instances have translate(text), see i18n
>
<App />
</TagoIOProvider>The provider reads its props once, when it mounts.
Plan for the following:
- Keep
"merge", or use"replace". The dashboard sends the widget's whole data set in every realtime message, so"append"stacks copies of it. allowedOriginsmust list every origin the dashboard runs on. Messages from any other origin are dropped, replies included, so a TagoRUN domain, custom domain or TagoDeploy host missing from the list leaves the widget loading and every call pending. Leave it out unless you know them all.
| Hook | Description |
|---|---|
useWidget() |
{ widget, isLoading, variables, dashboardId, widgetId, label }. isLoading stays true until the widget settings arrive |
useRealtimeData(options?) |
{ data, records, eventCount, lastUpdatedAt, clear }: the realtime blocks and their records, with an optional selector |
useResourceData() |
{ resources, getByType, refresh, eventCount, lastUpdatedAt }: platform resources (device list, users, entities) |
useUserInformation() |
{ userInformation, token, language, runURL, customPreferences, preferences }, empty until it arrives after the widget settings |
useBlueprintDevices() |
{ blueprintDevices, selected, settings }, filled when the dashboard sends blueprint device data. Read the selected devices from useWidget().variables |
useWidgetErrors() |
{ lastError, errors, clearErrors }: the failures the dashboard reports (Widget errors) |
useWidgetData() |
Convenience: combines widget + realtime + errors |
Every realtime message re-renders the components that call useRealtimeData, with or without a selector, because eventCount changes on each one. Filter records where you render them: each record carries its own variable and device.
const { records } = useRealtimeData();
const temperatures = records.filter((record) => record.variable === "temperature");selector receives the realtime blocks and returns the ones to keep, and data and records then hold only those. Return blocks from the array it receives, as filter does: a selector that builds new block objects makes React re-render until it throws.
| Hook | Returns |
|---|---|
useSendData() |
{ sendData, isSending, error, reset } |
useEditData() |
{ editData, isEditing, error, reset } |
useDeleteData() |
{ deleteData, isDeleting, error, reset } |
useEditResourceData() |
{ editResourceData, isEditing, error, reset } |
useCallEndpoint() |
{ callEndpoint, isCalling, error, reset } |
Each function returns a Promise that settles when the dashboard answers. The busy flag and error follow the latest call: the flag is true while that call waits for its answer, and error holds its rejection. An earlier call still settles its own promise but no longer changes them. reset() clears both and detaches the call in flight the same way, without cancelling it, so a reply that comes after a timeout leaves the hook idle.
What each function takes:
sendData(records): one record or an array, such as{ variable: "temperature", value: 25.5, unit: "°C" }.editData(records): each record'sidandvariablewith the newvalue, such as{ id: record.id, variable: record.variable, value: 30 }, addressed to the record's device assetToZerodoes below.deleteData(records): records withidanddevice, such as the ones inuseRealtimeData().records. The hook sends each one as a"<recordId>:<deviceId>"string.editResourceData(rows): see Editing resources.callEndpoint(endpointID, options?): see Calling an Analysis Endpoint.
// No request times out by itself, and some never get an answer (see the notes below).
function withTimeout<T>(promise: Promise<T>, ms = 10_000): Promise<T> {
let timeoutId = 0;
const timeout = new Promise<never>((_resolve, reject) => {
timeoutId = window.setTimeout(() => reject(new Error(`No reply from TagoIO after ${ms / 1000} seconds.`)), ms);
});
return Promise.race([promise, timeout]).finally(() => window.clearTimeout(timeoutId));
}
function SendButton() {
const { sendData, isSending, reset } = useSendData();
const [status, setStatus] = useState("");
async function send() {
try {
await withTimeout(sendData({ variable: "temperature", value: 25.5, unit: "°C" }));
setStatus("Stored.");
} catch (error) {
reset(); // isSending stays true while no reply comes
// A refused write rejects with the dashboard's reply, { status: false, message }.
setStatus(`Not confirmed: ${(error as { message?: string }).message}`);
}
}
return (
<p>
<button type="button" disabled={isSending} onClick={() => void send()}>
Send
</button>{" "}
{status}
</p>
);
}
function RecordActions({ record }: { record: TDataRecord }) {
const { variables } = useWidget();
const { editData, isEditing, reset: resetEdit } = useEditData();
const { deleteData, isDeleting, reset: resetDelete } = useDeleteData();
const [status, setStatus] = useState("");
async function setToZero() {
try {
// Address the edit to the device that holds the record (see below).
const binding = variables.find((item) => item.variable === record.variable && item.origin.id === record.device);
if (!binding) throw new Error("The record's device is not bound to the widget.");
const address = { device: binding.origin.id, origin: binding.origin.id, bucket: binding.origin.bucket };
await withTimeout(editData({ id: record.id, variable: record.variable, value: 0, ...address }));
setStatus("Saved.");
} catch (error) {
resetEdit();
// A missing binding, a refusal or a timeout. After a timeout, the edit may still go through.
setStatus(`Not confirmed: ${(error as { message?: string }).message}`);
}
}
async function remove() {
try {
await withTimeout(deleteData(record));
setStatus("Deleted.");
} catch (error) {
resetDelete();
setStatus(`Not confirmed: ${(error as { message?: string }).message}`);
}
}
return (
<p>
<button type="button" disabled={isEditing} onClick={() => void setToZero()}>
Set to 0
</button>{" "}
<button type="button" disabled={isDeleting} onClick={() => void remove()}>
Delete
</button>{" "}
{status}
</p>
);
}Plan for the following:
- Send after the widget settings arrive, and only bound variables. Wait until
useWidget().isLoadingisfalse.useSendDataanduseEditDatafill each record'sdeviceandoriginfrom the widget's binding for its variable, and drop a record whose variable is not bound. When they drop every record, the promise rejects with"No records to process". WhileisLoadingistrue, no variable is bound yet, and the dashboard ignores a request until it has handledready(), which the provider sends when it mounts, so a call made that early may never settle. - A variable bound on several devices is written to each. The hooks make one record per device the variable is bound on, and they always fill records this way. To send to a single device, bind the variable on that device only.
- Address each edit to the record's device. When a copy of an edit goes to a device that does not hold the record, the platform refuses the call, and the copies it handled before that one stay saved. Pass the
device,originandbucketof the binding for the record's device, assetToZerodoes: every copy then goes to the device that holds the record. When no binding matches that device, do not send the edit. - Addressed edits can still repeat. With the variable bound on several devices, the record's device gets one identical copy per binding. That is redundant but correct.
- A refused write rejects. When the platform refuses a
sendData,editDataordeleteData, the promise rejects with the dashboard's reply,{ status: false, message }, and the hook'serrorholds it until the next call orreset(). For an edit or a delete,messageis the platform's error or"Failed to edit"/"Failed to delete". A resolved promise means the platform accepted the change. - Keep a timeout for requests that get no answer. No request times out by itself. The dashboard ignores a request it gets before handling
ready(), and an older host, such as a TagoDeploy instance that has not been updated, may leave a refused request unanswered: the promise stays pending and the busy flag staystrue. Race each call against a timeout, aswithTimeoutdoes, and callreset()when it fires. On a current host, a refusal rejects the promise long before the timer fires. - Read
error.message. The dashboard's reply,{ status: false, message }, is a plain object, not anError. A record whosevariable,originandbucketmatch none of the widget's bindings gets"Invalid variable". The same reply also reachesuseWidgetErrors. A call made after the provider unmounted, a call still waiting when it unmounts, and a call whose recordspostMessagecannot copy reject with anErrorinstead, soerroris typedTError | Error. - Keep confirmed changes on screen. Realtime may not bring an edit or a delete back, and a later push can still carry the old record. Apply what you confirmed on top of
recordswhile realtime still shows the value from before the save, asedit-delete-data.tsxdoes.
The payload identity key depends on the resource type, and only columns listed in the resource's editable array are accepted (enforced server-side):
const { editResourceData } = useEditResourceData();
// Device row — identity key is `device`
await editResourceData({ device: "DEVICE_ID", name: "New name", "tags.type": "sensor" });
// User row — identity key is `user`
await editResourceData({ user: "USER_ID", phone: "+1 555 0100" });
// Entity row — row `id` plus the entity block id (resource.id)
await editResourceData({ id: "ROW_ID", entity: "ENTITY_ID", status: "closed" });Plan for the following:
- Keep entity rows and device or user rows in separate calls. The dashboard sends all the rows of one call to a single endpoint.
- Rows do not update by themselves. After a save, call
refresh()fromuseResourceData()to load device, user and entity_list rows again. Nothing replies to it, and any rows it loads arrive throughuseResourceData(). - Check entity results. An entity edit can resolve even when the platform refused it:
result.statusholds the HTTP status, andresult.datathe API answer, which can carrystatus: false. - Stop waiting after a while. The promise settles only when the dashboard answers, so race it against a timeout, as
withTimeoutdoes above.
useWidgetErrors() returns { lastError, errors, clearErrors }. It receives every failure the dashboard reports with status: false, except the ones that answer callEndpoint, which reject only that call's promise. A failure that answers another call carries that call's key and also rejects its promise, so you can handle it where you make the call. A record whose variable, origin and bucket match none of the widget's bindings gets "Invalid variable", and a call whose records the hook dropped gets "No records to process". The dashboard ignores a request it gets before handling ready(), and an older host, such as a TagoDeploy instance that has not been updated, may leave a failure unanswered or answer it without the key, as it does with "Failed to delete". Only this hook sees such a failure, if anything does, and its call never settles. Entries are plain objects with a message, not Error instances.
clearErrors() empties the list for every component under the provider. A mutation hook's reset() does not touch it.
function ErrorBanner() {
const { lastError, clearErrors } = useWidgetErrors();
if (!lastError) return null;
return (
<p role="alert">
{lastError.message}{" "}
<button type="button" onClick={clearErrors}>
Dismiss
</button>
</p>
);
}useNavigation() returns { openLink, closeModal }. openLink(url) asks the dashboard to open a link, and closeModal() asks it to close the modal the widget is in. Both return nothing, and no reply comes back.
import { TagoIOProvider, useNavigation } from "@tago-io/custom-widget-react";
function App() {
return (
<TagoIOProvider>
<Links />
</TagoIOProvider>
);
}
function Links() {
const { openLink, closeModal } = useNavigation();
// Wrap openLink in an arrow function: onClick={openLink} would pass the click event as the URL.
return (
<div>
{/* A dashboard, in the same tab. The query string preselects a blueprint device on it. */}
<button type="button" onClick={() => openLink("/dashboards/info/DASHBOARD_ID?IDENTIFIER=DEVICE_ID")}>
Open dashboard
</button>
{/* A web page, in a new tab. */}
<button type="button" onClick={() => openLink("https://docs.tago.io/docs/tagoio/widgets/custom-widget/")}>
Open the docs
</button>
{/* The modal a header button opened this widget in. */}
<button type="button" onClick={closeModal}>
Close
</button>
</div>
);
}Plan for the following:
- Dashboards open in the same tab. A link that contains
/dashboards/info/<dashboardId>opens that dashboard in the current tab, without a page reload, and keeps the query string. The dashboard drops everything before/dashboards/, so the relative form works on the Admin, TagoRUN and TagoDeploy domains alike. Keep/info/: the/dashboards/<id>address the browser bar shows is not treated as a dashboard link. - Blueprint devices are picked by Identifier. To preselect a device on a blueprint dashboard, add
?<identifier>=<deviceId>to the link, where<identifier>is the Identifier of one of that dashboard's blueprint devices. - Web pages open in a new tab. Any other full
https://URL opens in a new tab. The dashboard page opens that tab, and browsers block it when the click was not recent, so callopenLinkin the click handler itself, not after awaiting a request or a timer. - Use
openLink, not a plain link. An<a href>navigates the widget's own frame, not the dashboard around it. - Some links are not supported. These do nothing useful: Admin pages other than dashboards (
https://admin.tago.io/devices/<id>),mailto:andtel:links, bare e-mail addresses, and relative paths that are not dashboard links. In a dashboard embedded in another site,openLinkdoes nothing at all. In the TagoRUN mobile app, or a custom-branded app built on it, the dashboard hands the link to the app. closeModalonly closes a widget modal. A header button set to open a widget shows it in a modal, andcloseModalcloses that modal. On a dashboard tile it does nothing, and the widget cannot tell which of the two it is in. A header button set to open an iframe loads the page in a plain iframe, whereuseWidget().isLoadingstaystrueandcloseModaldoes nothing.- Closing removes the widget from the page. Let a pending
sendDataoreditDatacall settle beforecloseModal, or its reply is lost.
useRunAnalysis() returns only { runAnalysis }: no busy flag, no error and no promise. runAnalysis(scope) runs the Analysis selected in the widget settings, under Options > Run analysis when sending data. The widget gets the ID of that Analysis in widget.analysis_run.
function RunButton() {
const { widget } = useWidget();
const { runAnalysis } = useRunAnalysis();
const [requested, setRequested] = useState(false);
// The dashboard ignores runAnalysis while no Analysis is selected.
const hasAnalysis = Boolean(widget?.analysis_run);
return (
<button
type="button"
disabled={!hasAnalysis}
onClick={() => {
// The Analysis receives this array as its scope.
runAnalysis([{ zone: "north" }]);
setRequested(true);
}}
>
{requested ? "Requested" : "Run Analysis"}
</button>
);
}Plan for the following:
- Nothing runs without a selected Analysis. The dashboard ignores the call while
widget.analysis_runis empty, so keep the control disabled until it is set. - No reply comes back.
runAnalysisreturns nothing, and the widget never learns whether the Analysis ran or failed. To show a result, have the Analysis write to a variable the widget reads, and watchuseRealtimeDatafor the new record. - Send the scope as an array of plain objects. The Analysis receives that array as its
scope. A single object arrives wrapped in an array, and a string does not arrive as sent. The dashboard removes thesource,displayValueandorderingValuekeys from each item, and an item withsource: "entity"arrives rewritten as{ entity: origin, [variable]: value }, with a falsyvaluesent as"", so leave those keys out. - Wrap it in an arrow function.
onClick={runAnalysis}would send the click event as the scope, which the browser cannot copy into a message, so the call throws.
useCallEndpoint() returns { callEndpoint, isCalling, error, reset }. callEndpoint(endpointID, options?) calls the Endpoint of a Luau Analysis through the dashboard, which makes the call with the viewer's session, so no token goes in your code. endpointID is the Analysis ID, the one in its Endpoint URL. The Promise resolves with the Endpoint's answer, { status, headers, body }, for every HTTP status except a redirect, and rejects with a plain { code, message } object only when the call did not complete. isCalling is true while the call waits, error holds its rejection, and reset() clears both.
| Option | Default | Description |
|---|---|---|
method |
"GET" |
"GET", "POST", "PUT", "PATCH" or "DELETE" |
path |
"/" |
Below the Endpoint root, such as "/setpoint". The dashboard refuses . and .. segments |
query |
None | A plain object of strings, finite numbers and booleans, sent as text. An array repeats its key, and a key set to undefined is left out |
body |
None | A JSON value, encoded with JSON's rules. Not allowed with GET, the default method |
The form below saves a setpoint through the Analysis from the Validate a Custom Dashboard form recipe, which stores a value from 5 to 30 and answers 422 with a field error otherwise.
// The Analysis ID, the 24-character ID in its Endpoint URL.
const ENDPOINT_ID = "YOUR_ANALYSIS_ID";
type SetpointAnswer = { ok?: boolean; setpoint?: number; error?: string; errors?: { setpoint?: string } };
function SetpointForm() {
const { isLoading } = useWidget();
const { callEndpoint, isCalling, error } = useCallEndpoint();
const [setpoint, setSetpoint] = useState("22");
const [feedback, setFeedback] = useState("");
async function save() {
setFeedback("");
const answer = await callEndpoint<SetpointAnswer>(ENDPOINT_ID, {
method: "POST",
path: "/setpoint",
body: { setpoint },
}).catch(() => null);
// The hook rethrows: the call did not complete, and `error` holds { code, message }.
if (!answer) return;
// Every HTTP status except a redirect resolves, so check it before reading the body.
if (answer.status === 422) {
setFeedback(answer.body?.errors?.setpoint ?? "Invalid setpoint.");
} else if (answer.status >= 400) {
setFeedback(answer.body?.error ?? `Request failed (${answer.status}).`);
} else {
setFeedback(`Saved: ${answer.body?.setpoint ?? setpoint} C`);
}
}
return (
<form
noValidate
onSubmit={(event) => {
event.preventDefault();
void save();
}}
>
<input aria-label="Setpoint" value={setpoint} onChange={(event) => setSetpoint(event.target.value)} />
<button type="submit" disabled={isLoading || isCalling}>
Save
</button>
<p role="status">{error ? `Not completed (${error.code}): ${error.message}` : feedback}</p>
</form>
);
}The promise rejects with one of these codes:
code |
When |
|---|---|
bad_request |
endpointID is not a 24-character ID; options or its query is not a plain object; a query value is not a string, a finite number or a boolean; a body comes with GET, holds a value JSON cannot encode, such as a BigInt, or one JSON would send wrong, such as a Map or a top-level Date; options holds a value a message cannot carry; or the dashboard refused the request, such as an unknown method or a . or .. path segment. The Endpoint did not run |
api_error |
The dashboard could not complete the call: the Endpoint answered with a redirect, the network failed, or the reply was malformed. The Endpoint may have run, as it does before a redirect |
not_ready |
The widget settings have not arrived yet. Nothing is sent |
unsupported |
The dashboard does not support Endpoint calls from custom widgets. Nothing is sent |
aborted |
The TagoIOProvider unmounted, or an <Activity> hid it, before the dashboard answered or before the call was made. The message says whether the call was sent; one that was sent may have run |
Branch on code, and keep a default branch: a newer dashboard can send a code this table does not list.
Plan for the following:
- Read
statusfirst. Every HTTP answer except a redirect resolves, 4xx and 5xx included, and a script that runs longer than 30 seconds answers504.bodyis parsed when the response is JSON and is text otherwise, andheadersholds the response headers the browser can read, with lowercase names. Limits and errors lists what each status means. - The Run user needs Call Endpoint. The dashboard always sends the viewer's token, so in TagoRUN the Run user needs Call Endpoint on the Analysis in Access Management, separate from Run Analysis. Without it the answer is
404, even on a Public Endpoint (Choose who can call). - Call on a user action, not on a timer or on every realtime update. Every Endpoint call on the profile counts toward one allowance that all its callers share, 60 calls a minute on the Free plan, and a
429answer means it ran out. - Send a JSON value; a string is sent as text/plain, so the Analysis gets
scopeas nil and readscontext.request.body. Any other value is encoded with JSON's rules:toJSON()applies, as for aDateinside an object, and a value JSON cannot encode, such as aBigInt, rejects withbad_request. A value whose JSON is a bare string, such as a top-levelDate, rejects too, because the dashboard would send it as text: put it in an object. - Convert a
FormDataor aMapto a plain object. JSON writes aFormData,Map,Set,Blob, or a class instance that keeps its data in private fields, as{}, so a body that holds one, at any depth, rejects withbad_requestinstead of reaching the Analysis empty. Convert it first, for example withObject.fromEntries(formData). A class instance with fields is sent as its fields. - Disable the control while
useWidget().isLoadingorisCallingistrue. Until the widget settings arrive, the call rejects withnot_ready, and a click during a call starts another one. - Call from
useEffector an event handler, not fromuseLayoutEffect. A child's layout effects run before the provider's, so when an<Activity>shows the provider again, a call made in one finds the provider stopped and rejects withabortedwithout being sent. The data hooks reject such a call with anError, on a StrictMode replay too. isCallinganderrorfollow the latest call. An earlier call still settles its own promise but no longer changes them, andreset()detaches the call in flight the same way.- Catch inside the handler. The hook rethrows every rejection to its caller and also keeps it in
error. None reachesuseWidgetErrors. - Dashboards without the operation reject with
unsupported. With the widget settings, the dashboard lists the request operations it answers that older dashboards do not, today only"call-endpoint". On one without Endpoint calls for widgets, such as a TagoDeploy instance on an earlier Admin build,callEndpointrejects at once and sends nothing. - No custom headers, and redirects are refused. The dashboard sends the viewer's token and, for a JSON body,
Content-Type: application/json, and nothing else. An Endpoint that answers with a redirect still ran, but the call rejects withapi_errorand the redirect is not followed. To send the viewer elsewhere, return the URL in JSON and pass it toopenLinkfromuseNavigation().
useDictionary(options?) returns { t, tSync, dictionary, isLoading, language, error }. It translates through the class passed as the provider's dictionary prop, and returns the original text when there is no dictionary to ask:
t(text)resolves to whattranslate(text)returns on an instance of that class, created for the currentlanguage. Without adictionaryprop, before the language is known, or when the instance has notranslatemethod or it throws,tresolves to the original text.tpasses on whatevertranslatereturns, so have it return the original text for a key it does not know. TheDictionaryclass from@tago-io/sdkhas notranslatemethod, so pass a class of your own.tSync(text)returns the original text. Usetfor translations.languageisoptions.languagewhen you pass it, and otherwise the viewer's language from user information.
To show labels in the viewer's language without a dictionary class, keep your own translations and pick them by language:
const LABELS: Record<string, { save: string }> = {
en: { save: "Save" },
pt: { save: "Salvar" },
};
function SaveLabel() {
const { language } = useUserInformation();
// language is a locale tag such as "pt-BR", and null until user information arrives.
const labels = LABELS[language?.split(/[-_]/)[0] ?? "en"] ?? LABELS.en;
return <span>{labels.save}</span>;
}@tago-io/custom-widget-react re-exports these helpers from @tago-io/custom-widget-core. The JavaScript SDK does not include them.
declare function formatValue(
value: string | number | boolean | undefined,
options?: {
locale?: string;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
style?: "decimal" | "currency" | "percent" | "unit";
currency?: string;
unit?: string;
}
): string;
declare function formatDate(
date: string | Date | number,
options?: {
locale?: string;
dateStyle?: "full" | "long" | "medium" | "short";
timeStyle?: "full" | "long" | "medium" | "short";
relative?: boolean;
}
): string;
declare function groupByDevice(records: TDataRecord[]): Record<string, TDataRecord[]>; // key: device ID
declare function groupByVariable(records: TDataRecord[]): Record<string, TDataRecord[]>; // key: variable name
declare function getLatestByVariable(records: TDataRecord[]): Record<string, TDataRecord>; // newest record per variablefunction LatestTemperatures() {
const { records } = useRealtimeData();
const { language } = useUserInformation();
// Intl rejects tags such as "pt_BR", and undefined uses the browser's language.
const locale = language?.replace("_", "-");
return (
<ul>
{Object.entries(groupByDevice(records)).map(([deviceId, deviceRecords]) => {
const latest = getLatestByVariable(deviceRecords).temperature;
if (!latest) return null;
const value = formatValue(latest.value, { locale, maximumFractionDigits: 1 });
const unit = latest.unit ? ` ${latest.unit}` : "";
return (
<li key={deviceId}>
{deviceId}: {value}
{unit}, {formatDate(latest.time, { locale, relative: true })}
</li>
);
})}
</ul>
);
}Plan for the following:
- Group by device before picking the latest reading.
getLatestByVariableandgroupByVariablekey by variable name alone, so records from different devices with the same variable merge.groupByDevicekeys by each record'sdevice, falling back toorigin.getLatestByVariablecomparestimeas text. formatValuedoes not know TagoIO units. Numbers and numeric strings go throughIntl.NumberFormat. Other strings come back unchanged, booleans as"true"or"false",undefinedas""and an empty string as"0". Withstyle: "unit", Intl expects a unit such as"celsius": a unit like"°C"makes it fail, and you get the plain number. Appendrecord.unityourself.formatDateuses the browser's time zone. It has no time zone option, and it reads a number as milliseconds.relative: trueprints text such as"5 minutes ago", and"now", in English, for anything under a second.- User information arrives after the widget settings. Until it does,
languageisnull, and alocaleofundefineduses the browser's language.
A widget can ask the dashboard to scan a QR code or a barcode. In the TagoRUN mobile app, or a custom-branded app built on it, the app's own scanner opens. In a browser, whether TagoRUN on the web, Admin, or a widget embedded in another page, the page around the widget opens a camera scanner. The SDK does not wrap the scanner, so both the request and the reply are plain postMessage. The provider's own listener ignores them, so your listener runs alongside it.
import { useEffect, useState } from "react";
function ScanButton() {
const [label, setLabel] = useState("Scan barcode");
useEffect(() => {
function onMessage(event: MessageEvent) {
// Only the host page answers, and it is this widget's parent window. Opened on its own,
// `window.parent` is this page itself, so no message is a reply.
if (window.parent === window || event.source !== window.parent) {
return;
}
// The reply echoes the method you asked for. `data` holds the decoded string, or "" if the user canceled.
if (event.data?.method === "barcode") {
setLabel(event.data.data || "Canceled, scan again");
}
}
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, []);
// Ask for a scan from a click: in a browser, the request opens the camera.
return (
<button type="button" onClick={() => window.parent.postMessage({ method: "barcode" }, "*")}>
{label}
</button>
);
}Either method reads QR codes and 1D barcodes. The TagoRUN app may shape its scan window to the method, a square for qrcode and a wide strip for barcode, so ask for the one that matches the code. The reply echoes the method: a widget that asks for barcode is answered with barcode.
Plan for the following:
- In a browser, the scanner needs a camera. It also needs the user's permission to use it. Without either, the scanner shows an error and the user can only cancel. A page loaded inside another page's
<iframe>, such as a widget embedded with the embed code from Admin, also needsallow="camera"on every<iframe>around it, and every page around it served over HTTPS. - The reply comes when the user is done. It arrives once the user scans a code or cancels, and a cancel answers with an empty
data. An older host or app may never answer, so give the user a way to stop waiting instead of treating a slow reply as a failure. - The reply carries no
key. The SDK matches data-operation replies by thekeyit sends, but a scan reply never carries one, so it cannot be matched to its request. Keep a single request in flight, since one sent while a scan is open may get no answer of its own, and ignore a reply you are no longer waiting for.
The scan-code.tsx example adds the rest: one request at a time, a way to stop waiting, and late replies ignored.
The examples/ folder has ready-to-use .tsx files you can copy into your project:
- read-data.tsx: Display real-time data from devices
- send-data.tsx: Send data back to devices with a form
- read-resource.tsx: Read platform resources (device list, users, entities)
- edit-resource.tsx: Edit resource rows driven by the
editablecolumns - read-widget-info.tsx: Widget config, user info, and blueprint devices
- scan-code.tsx: Scan a QR code or barcode
- edit-delete-data.tsx: Edit and delete the data records a widget receives
- navigation.tsx: Open a dashboard or web page, or close a widget modal
- run-analysis.tsx: Run the widget's Analysis and show the data it writes
- format-data.tsx: Format the latest readings in the viewer's language
- call-endpoint.tsx: Save a setpoint through an Analysis Endpoint
All types and utilities from @tago-io/custom-widget-core are re-exported, so you only need one import source.
Apache-2.0 — see LICENSE.md for details.