react.mdx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. ---
  2. title: React
  3. description: Build terminal UIs with React and OpenTUI
  4. order: 2
  5. skill:
  6. entry: true
  7. intents: [react, jsx, hooks, keyboard, paste, focus, blur, selection, animation, testing]
  8. ---
  9. # React bindings
  10. Build terminal user interfaces using React with familiar patterns and components.
  11. ## Installation
  12. Quick start with [bun](https://bun.sh) and [create-tui](https://github.com/msmps/create-tui):
  13. ```bash
  14. bun create tui --template react
  15. ```
  16. Manual installation:
  17. ```bash
  18. bun install @opentui/react @opentui/core react
  19. ```
  20. ## Quick start
  21. ```tsx
  22. import { createCliRenderer } from "@opentui/core"
  23. import { createRoot } from "@opentui/react"
  24. function App() {
  25. return <text>Hello, world!</text>
  26. }
  27. const renderer = await createCliRenderer()
  28. createRoot(renderer).render(<App />)
  29. ```
  30. ## TypeScript configuration
  31. Configure your `tsconfig.json`:
  32. ```json
  33. {
  34. "compilerOptions": {
  35. "lib": ["ESNext", "DOM"],
  36. "target": "ESNext",
  37. "module": "ESNext",
  38. "moduleResolution": "bundler",
  39. "jsx": "react-jsx",
  40. "jsxImportSource": "@opentui/react",
  41. "strict": true,
  42. "skipLibCheck": true
  43. }
  44. }
  45. ```
  46. ## Runtime-loaded plugin support (if needed)
  47. If your app loads external TS/TSX modules at runtime (for example a file-based plugin system), import this once in your app entry before dynamic imports:
  48. ```ts
  49. import "@opentui/react/runtime-plugin-support"
  50. ```
  51. Use this for both normal Bun runs and standalone compiled executables.
  52. ## Components
  53. OpenTUI React provides JSX intrinsic elements that map to core renderables:
  54. ### Layout & display
  55. - `<text>` - Text display with styling
  56. - `<box>` - Container with borders and layout
  57. - `<scrollbox>` - Scrollable container
  58. - `<ascii-font>` - ASCII art text
  59. QR code support is available from `@opentui/qrcode/react` and must be registered explicitly with `registerQRCode()`.
  60. ### Input
  61. - `<input>` - Single-line text input
  62. - `<textarea>` - Multi-line text input
  63. - `<select>` - Selection list
  64. - `<tab-select>` - Tab-based selection
  65. ### Code & diff
  66. - `<code>` - Syntax-highlighted code
  67. - `<line-number>` - Line numbers with diff/diagnostic support
  68. - `<diff>` - Unified or split diff viewer
  69. - `<markdown>` - Markdown rendering
  70. ### Text modifiers
  71. Use inside `<text>` components:
  72. - `<span>` - Inline styled text
  73. - `<strong>`, `<b>` - Bold text
  74. - `<em>`, `<i>` - Italic text
  75. - `<u>` - Underlined text
  76. - `<br>` - Line break
  77. - `<a>` - Link text
  78. ## API reference
  79. ### `createRoot(renderer)`
  80. Creates a React root for rendering into the terminal.
  81. ```tsx
  82. import { createCliRenderer } from "@opentui/core"
  83. import { createRoot } from "@opentui/react"
  84. const renderer = await createCliRenderer()
  85. createRoot(renderer).render(<App />)
  86. ```
  87. For plugin slots, see [Plugin Slots overview](/docs/plugins/slots) and [React slots](/docs/plugins/react).
  88. ## Hooks
  89. ### `useRenderer()`
  90. Access the OpenTUI renderer instance.
  91. ```tsx
  92. import { useRenderer } from "@opentui/react"
  93. import { useEffect } from "react"
  94. function App() {
  95. const renderer = useRenderer()
  96. useEffect(() => {
  97. renderer.console.show()
  98. console.log("Hello from console!")
  99. }, [])
  100. return <box />
  101. }
  102. ```
  103. ### `useKeyboard(handler, options?)`
  104. Handle keyboard events.
  105. ```tsx
  106. import { useKeyboard, useRenderer } from "@opentui/react"
  107. function App() {
  108. const renderer = useRenderer()
  109. useKeyboard((key) => {
  110. if (key.name === "escape") {
  111. renderer.destroy()
  112. }
  113. })
  114. return <text>Press ESC to close</text>
  115. }
  116. ```
  117. To handle release events:
  118. ```tsx
  119. useKeyboard(
  120. (event) => {
  121. if (event.eventType === "release") {
  122. console.log("Key released:", event.name)
  123. } else {
  124. console.log("Key pressed:", event.name)
  125. }
  126. },
  127. { release: true },
  128. )
  129. ```
  130. ### `useOnResize(callback)`
  131. Handle terminal resize events.
  132. ```tsx
  133. import { useOnResize } from "@opentui/react"
  134. function App() {
  135. useOnResize((width, height) => {
  136. console.log(`Resized to ${width}x${height}`)
  137. })
  138. return <text>Resize-aware component</text>
  139. }
  140. ```
  141. ### `useTerminalDimensions()`
  142. Get reactive terminal dimensions.
  143. ```tsx
  144. import { useTerminalDimensions } from "@opentui/react"
  145. function App() {
  146. const { width, height } = useTerminalDimensions()
  147. return (
  148. <text>
  149. Terminal: {width}x{height}
  150. </text>
  151. )
  152. }
  153. ```
  154. ### `usePaste(handler)`
  155. Handle terminal paste events (bracketed paste).
  156. ```tsx
  157. import { decodePasteBytes } from "@opentui/core"
  158. import { usePaste } from "@opentui/react"
  159. function App() {
  160. usePaste((event) => {
  161. const text = decodePasteBytes(event.bytes)
  162. console.log("Pasted text:", text)
  163. })
  164. return <text>Paste something into the terminal</text>
  165. }
  166. ```
  167. ### `useFocus(handler)`
  168. Subscribe to terminal window focus events.
  169. ```tsx
  170. import { useFocus } from "@opentui/react"
  171. function App() {
  172. useFocus(() => {
  173. console.log("Terminal gained focus")
  174. })
  175. return <text>Focus-aware component</text>
  176. }
  177. ```
  178. ### `useBlur(handler)`
  179. Subscribe to terminal window blur events.
  180. ```tsx
  181. import { useBlur } from "@opentui/react"
  182. function App() {
  183. useBlur(() => {
  184. console.log("Terminal lost focus")
  185. })
  186. return <text>Blur-aware component</text>
  187. }
  188. ```
  189. ### `useSelectionHandler(handler)`
  190. Handle text selection events (e.g., mouse drag selection).
  191. ```tsx
  192. import { useSelectionHandler } from "@opentui/react"
  193. function App() {
  194. useSelectionHandler((selection) => {
  195. const text = selection.getSelectedText()
  196. console.log("Selected:", text)
  197. })
  198. return <text selectable>Select this text with your mouse</text>
  199. }
  200. ```
  201. ### `useTimeline(options?)`
  202. Create and manage animations.
  203. ```tsx
  204. import { useTimeline } from "@opentui/react"
  205. import { useEffect, useState } from "react"
  206. function App() {
  207. const [width, setWidth] = useState(0)
  208. const timeline = useTimeline({
  209. duration: 2000,
  210. loop: false,
  211. })
  212. useEffect(() => {
  213. timeline.add(
  214. { width },
  215. {
  216. width: 50,
  217. duration: 2000,
  218. ease: "linear",
  219. onUpdate: (animation) => {
  220. setWidth(animation.targets[0].width)
  221. },
  222. },
  223. )
  224. }, [])
  225. return <box style={{ width, backgroundColor: "#6a5acd" }} />
  226. }
  227. ```
  228. **Options:**
  229. - `duration` - Animation duration in ms (default: 1000)
  230. - `loop` - Whether to loop (default: false)
  231. - `autoplay` - Auto-start (default: true)
  232. - `onComplete` - Completion callback
  233. - `onPause` - Pause callback
  234. ## Styling
  235. Style components with props or the `style` prop:
  236. ```tsx
  237. // Direct props
  238. <box backgroundColor="blue" padding={2}>
  239. <text>Hello</text>
  240. </box>
  241. // Style prop
  242. <box style={{ backgroundColor: "blue", padding: 2 }}>
  243. <text>Hello</text>
  244. </box>
  245. ```
  246. ## Example: Login form
  247. ```tsx
  248. import { createCliRenderer } from "@opentui/core"
  249. import { createRoot, useKeyboard } from "@opentui/react"
  250. import { useCallback, useState } from "react"
  251. function App() {
  252. const [username, setUsername] = useState("")
  253. const [password, setPassword] = useState("")
  254. const [focused, setFocused] = useState<"username" | "password">("username")
  255. const [status, setStatus] = useState("idle")
  256. useKeyboard((key) => {
  257. if (key.name === "tab") {
  258. setFocused((prev) => (prev === "username" ? "password" : "username"))
  259. }
  260. })
  261. const handleSubmit = useCallback(() => {
  262. if (username === "admin" && password === "secret") {
  263. setStatus("success")
  264. } else {
  265. setStatus("error")
  266. }
  267. }, [username, password])
  268. return (
  269. <box style={{ border: true, padding: 2, flexDirection: "column", gap: 1 }}>
  270. <text fg="#FFFF00">Login Form</text>
  271. <box title="Username" style={{ border: true, width: 40, height: 3 }}>
  272. <input
  273. placeholder="Enter username..."
  274. onInput={setUsername}
  275. onSubmit={handleSubmit}
  276. focused={focused === "username"}
  277. />
  278. </box>
  279. <box title="Password" style={{ border: true, width: 40, height: 3 }}>
  280. <input
  281. placeholder="Enter password..."
  282. onInput={setPassword}
  283. onSubmit={handleSubmit}
  284. focused={focused === "password"}
  285. />
  286. </box>
  287. <text fg={status === "success" ? "green" : status === "error" ? "red" : "#999"}>{status.toUpperCase()}</text>
  288. </box>
  289. )
  290. }
  291. const renderer = await createCliRenderer()
  292. createRoot(renderer).render(<App />)
  293. ```
  294. ## Component extension
  295. Register custom renderables as JSX elements:
  296. ```tsx
  297. import { BoxRenderable, createCliRenderer, type BoxOptions, type RenderContext } from "@opentui/core"
  298. import { createRoot, extend } from "@opentui/react"
  299. class ConsoleButtonRenderable extends BoxRenderable {
  300. private _label: string = "Button"
  301. constructor(ctx: RenderContext, options: BoxOptions & { label?: string }) {
  302. super(ctx, options)
  303. if (options.label) this._label = options.label
  304. this.borderStyle = "single"
  305. this.padding = 2
  306. }
  307. get label(): string {
  308. return this._label
  309. }
  310. set label(value: string) {
  311. this._label = value
  312. this.requestRender()
  313. }
  314. }
  315. // Add TypeScript support
  316. declare module "@opentui/react" {
  317. interface OpenTUIComponents {
  318. consoleButton: typeof ConsoleButtonRenderable
  319. }
  320. }
  321. // Register the component
  322. extend({ consoleButton: ConsoleButtonRenderable })
  323. // Use in JSX
  324. function App() {
  325. return <consoleButton label="Click me!" style={{ border: true, backgroundColor: "green" }} />
  326. }
  327. const renderer = await createCliRenderer()
  328. createRoot(renderer).render(<App />)
  329. ```
  330. ## React DevTools
  331. OpenTUI React supports React DevTools for debugging:
  332. 1. Install:
  333. ```bash
  334. bun add --dev react-devtools-core@7
  335. ```
  336. 2. Start DevTools:
  337. ```bash
  338. npx react-devtools@7
  339. ```
  340. 3. Run with DEV flag:
  341. ```bash
  342. DEV=true bun run your-app.ts
  343. ```