React dialect
This page covers the ops of @pbuilder/sdk/react. How a dialect handle works, queries and .modify() are the same for every dialect and are described in Dialects.
@pbuilder/sdk/react mutates .tsx and .jsx files, and find() requires one of those two
extensions on the path. An extensionless path is rejected, never normalized, and any other
extension rejects with .tsx and .jsx are the only extensions the React dialect supports; a
.ts path points you to @pbuilder/sdk/typescript. The handle carries every
TypeScript dialect op (addImport, addDefaultImport,
sortImports and the rest) plus JSX and component ops, with .modify(fn) as the escape hatch
for everything else:
import * as react from "@pbuilder/sdk/react";
// src/Button.tsx before: const el = <Button />;await react .find("src/Button.tsx") .addImport("handleClick", "./handlers") .setJsxProp("Button", "onClick", "{handleClick}");// -> import { handleClick } from "./handlers";// -> const el = <Button onClick={handleClick} />;| Op | What it does |
|---|---|
setJsxProp(target, prop, value?) |
Sets a prop on the one element target names. value takes three forms: '"hi"' (string), '{count}' (expression), or omitted (boolean shorthand). |
removeJsxProp(target, prop) |
Removes a prop from the one element target names. An absent prop is a no-op, and a {...spread} is never touched, even when it may carry the prop. |
addJsxChild(target, jsx) |
Appends jsx, one JSX element or fragment, as the last child of the one element target names. A child with the same text already there is a no-op. |
wrapJsxElement(target, wrapper) |
Wraps the one element target names in wrapper, a self-closing JSX element whose props are kept. A no-op when the target is already directly inside that tag. |
renameJsxElement(target, tag) |
Renames the one element target names, opening and closing tag together. Imports are not touched. |
addHookCall(component, statement) |
Inserts one statement into the body of the component named component, after its leading hook calls. An identical statement already there is a no-op. |
addComponentProp(component, name, type, opts?) |
Adds name: type (name?: with { optional: true }) to the component’s props type and to its destructured parameter. The same name and type is a no-op; a different type rejects. |
The import ops are the TypeScript dialect’s own, with the same rules, so
addImport("React", "react") prints import { React } from "react". For
import React from "react", use addDefaultImport("React", "react").
Picking the element
Section titled “Picking the element”Every JSX op edits exactly one element, and rejects when zero or several elements match.
target is a tag name ("Button"), or an object that adds props
to narrow the match. A string prop value must equal the attribute’s initializer text as written
in the source, quotes included; true matches the prop with any value, shorthand included:
// src/App.tsx before:// <Routes>// <Route path="/" element={<Home />} />// <Route path="/users" element={<Users />} />// </Routes>await react .find("src/App.tsx") .setJsxProp({ tag: "Route", props: { path: '"/users"' } }, "caseSensitive");// -> <Route path="/users" element={<Users />} caseSensitive />A reject message names the tag and the prop names, never the prop values.
Children, wrappers and renames
Section titled “Children, wrappers and renames”addJsxChild puts the child on its own line at the siblings’ indentation, or inline when the
element’s content is inline. A self-closing target becomes an open/close pair. jsx must be
exactly one JSX element or fragment; anything else rejects without echoing it.
// src/App.tsx before:// <Routes>// <Route path="/" element={<Home />} />// </Routes>await react .find("src/App.tsx") .addImport("Users", "./pages/Users") .addJsxChild("Routes", '<Route path="/users" element={<Users />} />');// -> <Routes>// -> <Route path="/" element={<Home />} />// -> <Route path="/users" element={<Users />} />// -> </Routes>wrapJsxElement takes a self-closing wrapper and puts the target inside it:
// src/main.tsx before: root.render(<App />);await react.find("src/main.tsx").wrapJsxElement("App", "<QueryProvider client={queryClient} />");// -> root.render(<QueryProvider client={queryClient}><App /></QueryProvider>);renameJsxElement changes the opening and closing tag together. Nested elements with the same
tag are left alone, and renaming to the same tag is a no-op:
// src/Toolbar.tsx before: <Button onClick={save}>Save</Button>await react .find("src/Toolbar.tsx") .addImport("PrimaryButton", "./ui") .renameJsxElement("Button", "PrimaryButton");// -> <PrimaryButton onClick={save}>Save</PrimaryButton>None of these ops adds an import, so pair them with addImport.
Component ops
Section titled “Component ops”addHookCall and addComponentProp take a component name. The op looks for it among the
file’s top-level function Name declarations, exported or not, and top-level const Name =
arrow functions or function expressions. A wrapped component (memo(...), forwardRef(...))
is not found, and zero or several matches reject.
addHookCall(component, statement) inserts statement after the component’s leading hook
calls (statements that call useX(...) or React.useX(...)), or first when there are none,
at the body’s indentation. statement must be exactly one statement. An identical statement
already in the body is a no-op, and an expression-bodied arrow (() => <div />) rejects
because it has no statements to add to:
// src/Form.tsx before:// export function Form() {// const [name, setName] = useState("");// return <form />;// }await react.find("src/Form.tsx").addHookCall("Form", "const t = useTranslation();");// -> export function Form() {// -> const [name, setName] = useState("");// -> const t = useTranslation();// -> return <form />;// -> }addComponentProp(component, name, type, options?) adds name: type, or name?: type with
{ optional: true }, to the component’s props type. When the props parameter is destructured,
it also adds name to the destructuring, before a ...rest element. The props type is the
first parameter’s inline type literal, or an interface or type literal declared in the same
file and referenced by name. An imported or untyped props type rejects. A component without
parameters gets ({ name }: { name: type }). The same name with the same type text is a no-op,
and a different type rejects. type must be exactly one type:
// src/Card.tsx before:// interface CardProps {// title: string;// }// export function Card({ title }: CardProps) { ... }await react.find("src/Card.tsx").addComponentProp("Card", "subtitle", "string", { optional: true });// -> interface CardProps {// -> title: string;// -> subtitle?: string;// -> }// -> export function Card({ title, subtitle }: CardProps) { ... }Two React-specific subtleties:
- Spread precedence. An inserted prop lands after a trailing
{...spread}, so it wins at runtime under React’s later-position precedence:<Button {...rest} />plussetJsxProp("Button", "onClick", "{safe}")prints<Button {...rest} onClick={safe} />, andsafewins even ifrestalso supplies anonClick. - Collision rejects.
addImportfollows the TypeScript collision rules: anamealready bound some other way in the file rejects witha value or import binding named "X" already exists. There is no alias argument to route around it; renaming the existing binding or choosing a differentnameis on you.
setJsxProp’s value, addJsxChild’s jsx, wrapJsxElement’s wrapper, addHookCall’s
statement and addComponentProp’s type are emitted verbatim into executable code, with the
same trust boundary as the TypeScript source strings. The SDK checks that each is one JSX node,
one statement or one type, and rejects it without echoing it when it is not. It does no escaping
or sanitisation. By contrast, component, tag and prop names are validated name arguments and are
not a trusted-code channel.
.jsx files
Section titled “.jsx files”A .jsx file gets the same handle as a .tsx one. The SDK parses it as JavaScript with JSX, so
the JSX, hook and import ops behave as they do on .tsx:
// src/App.jsx before:// export default function App() {// return (// <Routes>// <Route path="/" element={<Home />} />// </Routes>// );// }await react .find("src/App.jsx") .addImport("Users", "./Users") .addHookCall("App", "const t = useTranslation();") .addJsxChild("Routes", '<Route path="/users" element={<Users />} />');A .jsx file cannot hold TypeScript syntax, so three ops reject on it at call time and leave the
file unchanged: addTypeImport, addComponentProp, and addClassProperty when you pass scope
or readonly. Without those two options, addClassProperty works on .jsx too. The error names
the op and says the edit needs .modify(), for example
addComponentProp is not available for .jsx files.
Example: add a <Route> (React)
Section titled “Example: add a <Route> (React)”addJsxChild skips a child only when the same text is already there. This factory uses
.modify() to skip the <Route> when any route already has that path, whatever its
element, and imports the page in the same write:
import { Routes, Route } from "react-router-dom";import { Home } from "./pages/Home";
export function App() { return ( <Routes> <Route path="/" element={<Home />} /> </Routes> );}import { find, astLibrary } from "@pbuilder/sdk/react";
export default async (input: { path: string; component: string }) => { await find("src/App.tsx") .addImport(input.component, `./pages/${input.component}`) .modify((ast) => { const routes = ast .getDescendantsOfKind(astLibrary.SyntaxKind.JsxElement) .find((el) => el.getOpeningElement().getTagNameNode().getText() === "Routes"); if (routes === undefined) { throw new Error("src/App.tsx has no <Routes> element"); }
const exists = routes .getDescendantsOfKind(astLibrary.SyntaxKind.JsxSelfClosingElement) .some((el) => { const attr = el.getAttribute("path"); return ( astLibrary.Node.isJsxAttribute(attr) && attr.getInitializer()?.getText() === JSON.stringify(input.path) ); }); if (exists) return;
const children = routes.getJsxChildren().map((child) => child.getText()).join("").trim(); routes.setBodyText(`${children}\n<Route path="${input.path}" element={<${input.component} />} />`); });};import { Routes, Route } from "react-router-dom";import { Home } from "./pages/Home";import { Pricing } from "./pages/Pricing";
export function App() { return ( <Routes> <Route path="/" element={<Home />} /> <Route path="/pricing" element={<Pricing />} /> </Routes> );}This factory checks before it edits, so a re-run writes nothing: the same idempotency the named ops give you.