React for CLIs. Build and test your CLI output using components.
Ink provides the same component-based UI building experience that React offers in the browser, but for command-line apps.
It uses Yoga to build Flexbox layouts in the terminal, so most CSS-like properties are available in Ink as well.
If you are already familiar with React, you already know Ink.
Since Ink is a React renderer, all features of React are supported.
Head over to the React website for documentation on how to use it.
Only Ink’s methods are documented in this readme.
Use create-ink-app to quickly scaffold a new Ink-based CLI.
npx create-ink-app my-ink-cli
Alternatively, create a TypeScript project:
npx create-ink-app --typescript my-ink-cli
Manual JavaScript setup
Ink requires the same Babel setup as you would do for regular React-based apps in the browser.
Set up Babel with a React preset to ensure all examples in this readme work as expected.
After installing Babel, install @babel/preset-react and insert the following configuration in babel.config.json:
npm install --save-dev @babel/preset-react
{
"presets": ["@babel/preset-react"]
}
Next, create a file source.js, where you’ll type code that uses Ink:
import React from 'react';
import {render, Text} from 'ink';
const Demo = () => <Text>Hello World</Text>;
render(<Demo />);
Then, transpile this file with Babel:
npx babel source.js -o cli.js
Now you can run cli.js with Node.js:
node cli
If you don’t like transpiling files during development, you can use import-jsx or @esbuild-kit/esm-loader to import a JSX file and transpile it on the fly.
Ink uses Yoga, a Flexbox layout engine, to build great user interfaces for your CLIs using familiar CSS-like properties you’ve used when building apps for the browser.
It’s important to remember that each element is a Flexbox container.
Think of it as if every <div> in the browser had display: flex.
See <Box> built-in component below for documentation on how to use Flexbox layouts in Ink.
Note that all text must be wrapped in a <Text> component.
App Lifecycle
An Ink app is a Node.js process, so it stays alive only while there is active work in the event loop (timers, pending promises, useInput listening on stdin, etc.). If your component tree has no async work, the app will render once and exit immediately.
To exit the app, press Ctrl+C (enabled by default via exitOnCtrlC), call exit() from useApp inside a component, or call unmount() on the object returned by render().
This component can display text and change its style to make it bold, underlined, italic, or strikethrough.
import {render, Text} from 'ink';
const Example = () => (
<>
<Text color="green">I am green</Text>
<Text color="black" backgroundColor="white">
I am black on white
</Text>
<Text color="#ffffff">I am white</Text>
<Text bold>I am bold</Text>
<Text italic>I am italic</Text>
<Text underline>I am underline</Text>
<Text strikethrough>I am strikethrough</Text>
<Text inverse>I am inversed</Text>
</>
);
render(<Example />);
[!NOTE]
<Text> allows only text nodes and nested <Text> components inside of it. For example, <Box> component can’t be used inside <Text>.
color
Type: string
Change text color.
Ink uses chalk under the hood, so all its functionality is supported.
This property tells Ink to wrap or truncate text if its width is larger than the container.
If wrap is passed (the default), Ink will wrap text and split it into multiple lines.
If truncate-* is passed, Ink will truncate text instead, resulting in one line of text with the rest cut off.
<Box width={7}>
<Text>Hello World</Text>
</Box>
//=> 'Hello\nWorld'
// `truncate` is an alias to `truncate-end`
<Box width={7}>
<Text wrap="truncate">Hello World</Text>
</Box>
//=> 'Hello…'
<Box width={7}>
<Text wrap="truncate-middle">Hello World</Text>
</Box>
//=> 'He…ld'
<Box width={7}>
<Text wrap="truncate-start">Hello World</Text>
</Box>
//=> '…World'
<Box>
<Box> is an essential Ink component to build your layout.
It’s like <div style="display: flex"> in the browser.
import {render, Box, Text} from 'ink';
const Example = () => (
<Box margin={2}>
<Text>This is a box with margin</Text>
</Box>
);
render(<Example />);
Dimensions
width
Type: numberstring
Width of the element in spaces.
You can also set it as a percentage, which will calculate the width based on the width of the parent element.
Sets a minimum height of the element in lines (rows).
You can also set it as a percentage, which will calculate the minimum height based on the height of the parent element.
Sets a maximum height of the element in lines (rows).
You can also set it as a percentage, which will calculate the maximum height based on the height of the parent element.
aspectRatio
Type: number
Defines the aspect ratio (width/height) for the element.
Use it with at least one size constraint (width, height, minHeight, or maxHeight) so Ink can derive the missing dimension.
Padding
paddingTop
Type: number Default: 0
Top padding.
paddingBottom
Type: number Default: 0
Bottom padding.
paddingLeft
Type: number Default: 0
Left padding.
paddingRight
Type: number Default: 0
Right padding.
paddingX
Type: number Default: 0
Horizontal padding. Equivalent to setting paddingLeft and paddingRight.
paddingY
Type: number Default: 0
Vertical padding. Equivalent to setting paddingTop and paddingBottom.
padding
Type: number Default: 0
Padding on all sides. Equivalent to setting paddingTop, paddingBottom, paddingLeft and paddingRight.
<Box paddingTop={2}><Text>Top</Text></Box>
<Box paddingBottom={2}><Text>Bottom</Text></Box>
<Box paddingLeft={2}><Text>Left</Text></Box>
<Box paddingRight={2}><Text>Right</Text></Box>
<Box paddingX={2}><Text>Left and right</Text></Box>
<Box paddingY={2}><Text>Top and bottom</Text></Box>
<Box padding={2}><Text>Top, bottom, left and right</Text></Box>
Margin
marginTop
Type: number Default: 0
Top margin.
marginBottom
Type: number Default: 0
Bottom margin.
marginLeft
Type: number Default: 0
Left margin.
marginRight
Type: number Default: 0
Right margin.
marginX
Type: number Default: 0
Horizontal margin. Equivalent to setting marginLeft and marginRight.
marginY
Type: number Default: 0
Vertical margin. Equivalent to setting marginTop and marginBottom.
margin
Type: number Default: 0
Margin on all sides. Equivalent to setting marginTop, marginBottom, marginLeft and marginRight.
<Box marginTop={2}><Text>Top</Text></Box>
<Box marginBottom={2}><Text>Bottom</Text></Box>
<Box marginLeft={2}><Text>Left</Text></Box>
<Box marginRight={2}><Text>Right</Text></Box>
<Box marginX={2}><Text>Left and right</Text></Box>
<Box marginY={2}><Text>Top and bottom</Text></Box>
<Box margin={2}><Text>Top, bottom, left and right</Text></Box>
Gap
gap
Type: number Default: 0
Size of the gap between an element’s columns and rows. A shorthand for columnGap and rowGap.
<Box gap={1} width={3} flexWrap="wrap">
<Text>A</Text>
<Text>B</Text>
<Text>C</Text>
</Box>
// A B
//
// C
columnGap
Type: number Default: 0
Size of the gap between an element’s columns.
<Box columnGap={1}>
<Text>A</Text>
<Text>B</Text>
</Box>
// A B
rowGap
Type: number Default: 0
Size of the gap between an element’s rows.
<Box flexDirection="column" rowGap={1}>
<Text>A</Text>
<Text>B</Text>
</Box>
// A
//
// B
<Box>
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>Y</Text>
</Box>
// X Y
<Box flexDirection="row-reverse">
<Text>X</Text>
<Box marginRight={1}>
<Text>Y</Text>
</Box>
</Box>
// Y X
<Box flexDirection="column">
<Text>X</Text>
<Text>Y</Text>
</Box>
// X
// Y
<Box flexDirection="column-reverse">
<Text>X</Text>
<Text>Y</Text>
</Box>
// Y
// X
<Box alignItems="flex-start">
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>
A
<Newline/>
B
<Newline/>
C
</Text>
</Box>
// X A
// B
// C
<Box alignItems="center">
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>
A
<Newline/>
B
<Newline/>
C
</Text>
</Box>
// A
// X B
// C
<Box alignItems="flex-end">
<Box marginRight={1}>
<Text>X</Text>
</Box>
<Text>
A
<Newline/>
B
<Newline/>
C
</Text>
</Box>
// A
// B
// X C
alignSelf
Type: string Default: auto Allowed values: autoflex-startcenterflex-endstretchbaseline
Defines alignment between flex lines on the cross axis when flexWrap creates multiple lines.
See align-content.
Unlike CSS (stretch), Ink defaults to flex-start so wrapped lines stay compact and fixed-height boxes don’t gain unexpected empty rows unless you opt in to stretching.
Add a border with a specified style.
If borderStyle is undefined (the default), no border will be added.
Ink uses border styles from the cli-boxes module.
A flexible space that expands along the major axis of its containing layout.
It’s useful as a shortcut for filling all the available space between elements.
For example, using <Spacer> in a <Box> with default flex direction (row) will position “Left” on the left side and will push “Right” to the right side.
In a vertical flex direction (column), it will position “Top” at the top of the container and push “Bottom” to the bottom.
Note that the container needs to be tall enough to see this in effect.
<Static> component permanently renders its output above everything else.
It’s useful for displaying activity like completed tasks or logs - things that
don’t change after they’re rendered (hence the name “Static”).
It’s preferred to use <Static> for use cases like these when you can’t know
or control the number of items that need to be rendered.
For example, Tap uses <Static> to display
a list of completed tests. Gatsby uses it
to display a list of generated pages while still displaying a live progress bar.
import React, {useState, useEffect} from 'react';
import {render, Static, Box, Text} from 'ink';
const Example = () => {
const [tests, setTests] = useState([]);
useEffect(() => {
let completedTests = 0;
let timer;
const run = () => {
// Fake 10 completed tests
if (completedTests++ < 10) {
setTests(previousTests => [
...previousTests,
{
id: previousTests.length,
title: `Test #${previousTests.length + 1}`
}
]);
timer = setTimeout(run, 100);
}
};
run();
return () => {
clearTimeout(timer);
};
}, []);
return (
<>
{/* This part will be rendered once to the terminal */}
<Static items={tests}>
{test => (
<Box key={test.id}>
<Text color="green">✔ {test.title}</Text>
</Box>
)}
</Static>
{/* This part keeps updating as state changes */}
<Box marginTop={1}>
<Text dimColor>Completed tests: {tests.length}</Text>
</Box>
</>
);
};
render(<Example />);
[!NOTE]
<Static> only renders new items in the items prop and ignores items
that were previously rendered. This means that when you add new items to the items
array, changes you make to previous items will not trigger a rerender.
See examples/static for an example usage of <Static> component.
items
Type: Array
Array of items of any type to render using the function you pass as a component child.
style
Type: object
Styles to apply to a container of child elements.
See <Box> for supported properties.
Function that is called to render every item in the items array.
The first argument is the item itself, and the second argument is the index of that item in the
items array.
Note that a key must be assigned to the root component.
<Static items={['a', 'b', 'c']}>
{(item, index) => {
// This function is called for every item in ['a', 'b', 'c']
// `item` is 'a', 'b', 'c'
// `index` is 0, 1, 2
return (
<Box key={index}>
<Text>Item: {item}</Text>
</Box>
);
}}
</Static>
<Transform>
Transform a string representation of React components before they’re written to output.
For example, you might want to apply a gradient to text, add a clickable link, or create some text effects.
These use cases can’t accept React nodes as input; they expect a string.
That’s what the <Transform> component does: it gives you an output string of its child components and lets you transform it in any way.
[!NOTE]
<Transform> must be applied only to <Text> children components and shouldn’t change the dimensions of the output; otherwise, the layout will be incorrect.
[!IMPORTANT]
When children use <Text> styling props (e.g. color, bold), the string passed to transform will contain ANSI escape codes. If your transform manipulates whitespace or does string operations like .trim(), you may need to use ANSI-aware methods (e.g. from slice-ansi or strip-ansi).
Since the transform function converts all characters to uppercase, the final output rendered to the terminal will be “HELLO WORLD”, not “Hello World”.
When the output wraps to multiple lines, it can be helpful to know which line is being processed.
For example, to implement a hanging indent component, you can indent all the lines except for the first.
import {render, Transform} from 'ink';
const HangingIndent = ({indent = 4, children}) => (
<Transform
transform={(line, index) =>
index === 0 ? line : ' '.repeat(indent) + line
}
>
{children}
</Transform>
);
const text =
'WHEN I WROTE the following pages, or rather the bulk of them, ' +
'I lived alone, in the woods, a mile from any neighbor, in a ' +
'house which I had built myself, on the shore of Walden Pond, ' +
'in Concord, Massachusetts, and earned my living by the labor ' +
'of my hands only. I lived there two years and two months. At ' +
'present I am a sojourner in civilized life again.';
render(
<HangingIndent indent={4}>
{text}
</HangingIndent>
);
transform(outputLine, index)
Type: Function
Function that transforms children output.
It accepts children and must return transformed children as well.
children
Type: string
Output of child components.
index
Type: number
The zero-indexed line number of the line that’s currently being transformed.
Hooks
useInput(inputHandler, options?)
A React hook that returns void and handles user input.
It’s a more convenient alternative to using useStdin and listening for data events.
The callback you pass to useInput is called for each character when the user enters any input.
However, if the user pastes text and it’s more than one character, the callback will be called only once, and the whole string will be passed as input.
You can find a full example of using useInput at examples/use-input.
import {useInput} from 'ink';
const UserInput = () => {
useInput((input, key) => {
if (input === 'q') {
// Exit program
}
if (key.leftArrow) {
// Left arrow key pressed
}
});
return …
};
inputHandler(input, key)
Type: Function
The handler function that you pass to useInput receives two arguments:
input
Type: string
The input that the program received.
key
Type: object
Handy information about a key that was pressed.
key.leftArrow
key.rightArrow
key.upArrow
key.downArrow
Type: boolean Default: false
If an arrow key was pressed, the corresponding property will be true.
For example, if the user presses the left arrow key, key.leftArrow equals true.
key.return
Type: boolean Default: false
Return (Enter) key was pressed.
key.escape
Type: boolean Default: false
Escape key was pressed.
key.ctrl
Type: boolean Default: false
Ctrl key was pressed.
key.shift
Type: boolean Default: false
Shift key was pressed.
key.tab
Type: boolean Default: false
Tab key was pressed.
key.backspace
Type: boolean Default: false
Backspace key was pressed.
key.delete
Type: boolean Default: false
Delete key was pressed.
key.pageDown
key.pageUp
Type: boolean Default: false
If the Page Up or Page Down key was pressed, the corresponding property will be true.
For example, if the user presses Page Down, key.pageDown equals true.
key.home
key.end
Type: boolean Default: false
If the Home or End key was pressed, the corresponding property will be true.
For example, if the user presses End, key.end equals true.
The type of key event. Only available with kitty keyboard protocol. Without the protocol, this property is undefined.
options
Type: object
isActive
Type: boolean Default: true
Enable or disable capturing of user input.
Useful when there are multiple useInput hooks used at once to avoid handling the same input several times.
usePaste(handler, options?)
A React hook that calls handler whenever the user pastes text. Bracketed paste mode (\x1b[?2004h) is automatically enabled while the hook is active, so pasted text arrives as a single string rather than being misinterpreted as individual key presses.
usePaste and useInput can be used together in the same component. They operate on separate event channels, so paste content is never forwarded to useInput handlers when usePaste is active.
import {useInput, usePaste} from 'ink';
const MyInput = () => {
useInput((input, key) => {
// Only receives typed characters and key events, not pasted text.
if (key.return) {
// Submit
}
});
usePaste((text) => {
// Receives the full pasted string, including newlines.
console.log('Pasted:', text);
});
return …
};
handler(text)
Type: Function
Called with the full pasted string whenever the user pastes text. The string is delivered verbatim — newlines, escape sequences, and other special characters are preserved exactly as pasted.
text
Type: string
The pasted text.
options
Type: object
isActive
Type: boolean Default: true
Enable or disable the paste handler. Useful when multiple components use usePaste and only one should be active at a time.
useApp()
A React hook that returns app lifecycle methods.
exit(errorOrResult?)
Type: Function
Exit (unmount) the whole Ink app.
errorOrResult
Type: Error | unknown
Optional value that controls how waitUntilExit settles:
exit() resolves with undefined.
exit(error) rejects when error is an Error.
exit(value) resolves with value.
import {useEffect} from 'react';
import {useApp} from 'ink';
const Example = () => {
const {exit} = useApp();
// Exit the app after 5 seconds
useEffect(() => {
setTimeout(() => {
exit();
}, 5000);
}, [exit]);
return …
};
waitUntilRenderFlush()
Type: Function
Returns a promise that settles after pending render output is flushed to stdout.
A React hook that returns the stdin stream and stdin-related utilities.
stdin
Type: stream.Readable Default: process.stdin
The stdin stream passed to render() in options.stdin, or process.stdin by default.
Useful if your app needs to handle user input.
import {useStdin} from 'ink';
const Example = () => {
const {stdin} = useStdin();
return …
};
isRawModeSupported
Type: boolean
A boolean flag determining if the current stdin supports setRawMode.
A component using setRawMode might want to use isRawModeSupported to nicely fall back in environments where raw mode is not supported.
A React hook that returns the stdout stream where Ink renders your app and stdout-related utilities.
stdout
Type: stream.Writable Default: process.stdout
import {useStdout} from 'ink';
const Example = () => {
const {stdout} = useStdout();
return …
};
write(data)
Write any string to stdout while preserving Ink’s output.
It’s useful when you want to display external information outside of Ink’s rendering and ensure there’s no conflict between the two.
It’s similar to <Static>, except it can’t accept components; it only works with strings.
data
Type: string
Data to write to stdout.
import {useStdout} from 'ink';
const Example = () => {
const {write} = useStdout();
useEffect(() => {
// Write a single message to stdout, above Ink's output
write('Hello from Ink to stdout\n');
}, []);
return …
};
A React hook that returns the current layout metrics for a tracked box element.
It updates when layout changes (for example terminal resize, sibling/content changes, or position changes).
Use hasMeasured to detect when the currently tracked element has been measured.
Whether the currently tracked element has been measured.
[!NOTE]
The hook returns {width: 0, height: 0, left: 0, top: 0} until the first layout pass completes. It also returns zeros when the tracked ref is detached.
useStderr()
A React hook that returns the stderr stream and stderr-related utilities.
stderr
Type: stream.Writable Default: process.stderr
Stderr stream.
import {useStderr} from 'ink';
const Example = () => {
const {stderr} = useStderr();
return …
};
write(data)
Write any string to stderr while preserving Ink’s output.
It’s useful when you want to display external information outside of Ink’s rendering and ensure there’s no conflict between the two.
It’s similar to <Static>, except it can’t accept components; it only works with strings.
data
Type: string
Data to write to stderr.
import {useStderr} from 'ink';
const Example = () => {
const {write} = useStderr();
useEffect(() => {
// Write a single message to stderr, above Ink's output
write('Hello from Ink to stderr\n');
}, []);
return …
};
useWindowSize()
A React hook that returns the current terminal dimensions and re-renders the component whenever the terminal is resized.
import {Text, useWindowSize} from 'ink';
const Example = () => {
const {columns, rows} = useWindowSize();
return <Text>{columns}x{rows}</Text>;
};
columns
Type: number
Number of columns (horizontal character cells).
rows
Type: number
Number of rows (vertical character cells).
useFocus(options?)
A React hook that returns focus state and focus controls for the current component.
A component that uses the useFocus hook becomes “focusable” to Ink, so when the user presses Tab, Ink will switch focus to this component.
If there are multiple components that execute the useFocus hook, focus will be given to them in the order in which these components are rendered.
This hook returns an object with an isFocused boolean property, which determines whether this component is focused.
options
autoFocus
Type: boolean Default: false
Auto-focus this component if there’s no active (focused) component right now.
isActive
Type: boolean Default: true
Enable or disable this component’s focus, while still maintaining its position in the list of focusable components.
This is useful for inputs that are temporarily disabled.
id
Type: string Required: false
Set a component’s focus ID, which can be used to programmatically focus the component. This is useful for large interfaces with many focusable elements to avoid having to cycle through all of them.
import {render, useFocus, Text} from 'ink';
const Example = () => {
const {isFocused} = useFocus();
return <Text>{isFocused ? 'I am focused' : 'I am not focused'}</Text>;
};
render(<Example />);
Switch focus to the next focusable component.
If there’s no active component right now, focus will be given to the first focusable component.
If the active component is the last in the list of focusable components, focus will be switched to the first focusable component.
[!NOTE]
Ink calls this method when user presses Tab.
Switch focus to the previous focusable component.
If there’s no active component right now, focus will be given to the first focusable component.
If the active component is the first in the list of focusable components, focus will be switched to the last focusable component.
[!NOTE]
Ink calls this method when user presses Shift+Tab.
A React hook that returns methods to control the terminal cursor position after each render.
This is essential for IME (Input Method Editor) support, where the composing character is displayed at the cursor location.
Configure whether Ink should listen for Ctrl+C keyboard input and exit the app.
This is needed in case process.stdin is in raw mode, because then Ctrl+C is ignored by default and the process is expected to handle it manually.
patchConsole
Type: boolean Default: true
Patch console methods to ensure console output doesn’t mix with Ink’s output.
When any of the console.* methods are called (like console.log()), Ink intercepts their output, clears the main output, renders output from the console method, and then rerenders the main output again.
That way, both are visible and don’t overlap each other.
This functionality is powered by patch-console, so if you need to disable Ink’s interception of output but want to build something custom, you can use that.
Runs the given callback after each render and re-render with render metrics.
This callback runs after Ink commits a frame, but it does not wait for stdout/stderr stream callbacks.
To run code after output is flushed, use waitUntilRenderFlush().
If true, each update will be rendered as separate output, without replacing the previous one.
maxFps
Type: number Default: 30
Maximum frames per second for render updates.
This controls how frequently the UI can update to prevent excessive re-rendering.
Higher values allow more frequent updates but may impact performance.
Setting it to a lower value may be useful for components that update very frequently, to reduce CPU usage.
incrementalRendering
Type: boolean Default: false
Enable incremental rendering mode which only updates changed lines instead of redrawing the entire output.
This can reduce flickering and improve performance for frequently updating UIs.
concurrent
Type: boolean Default: false
Enable React Concurrent Rendering mode.
When enabled:
Suspense boundaries work correctly with async data fetching
useTransition and useDeferredValue hooks are fully functional
Updates can be interrupted for higher priority work
render(<MyApp />, {concurrent: true});
[!NOTE]
Concurrent mode changes the timing of renders. Some tests may need to use act() to properly await updates. The concurrent option only takes effect on the first render for a given stdout. If you need to change the rendering mode, call unmount() first.
interactive
Type: boolean Default: true (false if in CI (detected via is-in-ci) or stdout.isTTY is falsy)
Override automatic interactive mode detection.
By default, Ink detects whether the environment is interactive based on CI detection and stdout.isTTY. When non-interactive, Ink skips terminal-specific features like ANSI erase sequences, cursor manipulation, synchronized output, resize handling, and kitty keyboard auto-detection. Only the final frame of non-static output is written at unmount.
Most users should not need to set this option. Use it when you have your own “interactive” detection logic that differs from the built-in behavior.
// Use your own detection logic
const isInteractive = myCustomDetection();
render(<MyApp />, {interactive: isInteractive});
kittyKeyboard
Type: object Default: undefined
Enable the kitty keyboard protocol for enhanced keyboard input handling. When enabled, terminals that support the protocol will report additional key information including super, hyper, capsLock, numLock modifiers and eventType (press/repeat/release).
import {render} from 'ink';
render(<MyApp />, {kittyKeyboard: {mode: 'auto'}});
'auto': Detect terminal support using a heuristic precheck (known terminals like kitty, WezTerm, Ghostty) followed by a protocol query confirmation (CSI ? u). The protocol is only enabled if the terminal responds to the query within a short timeout.
'enabled': Force enable the protocol. Both stdin and stdout must be TTYs.
'reportAllKeysAsEscapeCodes' - Report all keys as escape codes
'reportAssociatedText' - Report associated text with key events
Behavior notes
When the kitty keyboard protocol is enabled, input handling changes in several ways:
Non-printable keys produce empty input. Keys like function keys (F1-F35), modifier-only keys (Shift, Control, Super), media keys, Caps Lock, Print Screen, and similar keys will not produce any text in the input parameter of useInput. They can still be detected via the key object properties.
Ctrl+letter shortcuts work as expected. When the terminal sends Ctrl+letter as codepoint 1-26 (the kitty CSI-u alternate form), input is set to the letter name (e.g. 'c' for Ctrl+C) and key.ctrl is true. This ensures exitOnCtrlC and custom Ctrl+letter handlers continue to work regardless of which codepoint form the terminal uses.
Key disambiguation. The protocol allows the terminal to distinguish between keys that normally produce the same escape sequence. For example:
Ctrl+I vs Tab - without the protocol, both produce the same byte (\x09). With the protocol, they are reported as distinct keys.
Shift+Enter vs Enter - the shift modifier is correctly reported.
Escape key vs Ctrl+[ - these are disambiguated.
Event types. With the reportEventTypes flag, key press, repeat, and release events are distinguished via key.eventType.
renderToString(tree, options?)
Returns: string
Render a React element to a string synchronously. Unlike render(), this function does not write to stdout, does not set up any terminal event listeners, and returns the rendered output as a string.
Useful for generating documentation, writing output to files, testing, or any scenario where you need the rendered output as a string without starting a persistent terminal application.
Terminal-specific hooks (useInput, useStdin, useStdout, useStderr, useWindowSize, useApp, useFocus, useFocusManager) return default no-op values since there is no terminal session. They will not throw, but they will not function as in a live terminal.
useEffect callbacks will execute during rendering (due to synchronous rendering mode), but state updates they trigger will not affect the returned output, which reflects the initial render.
useLayoutEffect callbacks fire synchronously during commit, so state updates they trigger will be reflected in the output.
The <Static> component is supported — its output is prepended to the dynamic output.
If a component throws during rendering, the error is propagated to the caller after cleanup.
tree
Type: ReactNode
options
Type: object
columns
Type: number Default: 80
Width of the virtual terminal in columns. Controls where text wrapping occurs.
const output = renderToString(<Text>{'A'.repeat(100)}</Text>, {
columns: 40,
});
// Text wraps at 40 columns
Instance
This is the object that render() returns.
rerender(tree)
Replace the previous root node with a new one or update the props of the current root node.
Returns a promise that settles when the app is unmounted.
It resolves with the value passed to exit(value) and rejects with the error passed to exit(error).
When unmount() is called manually, it settles after unmount-related stdout writes complete.
const {unmount, waitUntilExit} = render(<MyApp />);
setTimeout(unmount, 1000);
await waitUntilExit(); // resolves after `unmount()` is called
waitUntilRenderFlush()
Returns a promise that settles after pending render output is flushed to stdout.
Useful when you need to run code only after a frame is written:
const {rerender, waitUntilRenderFlush} = render(<MyApp step="loading" />);
rerender(<MyApp step="ready" />);
await waitUntilRenderFlush(); // output for "ready" is flushed
runNextCommand();
cleanup()
Delete the internal Ink instance associated with the current stdout.
This is mostly useful for advanced cases (for example, tests) where you need render() to create a fresh instance for the same stream.
This does not unmount the current app.
clear()
Clear output.
const {clear} = render(<MyApp />);
clear();
measureElement(ref)
Measure the dimensions of a particular <Box> element.
Returns an object with width and height properties.
This function is useful when your component needs to know the amount of available space it has. You can use it when you need to change the layout based on the length of its content.
[!NOTE]
measureElement() returns {width: 0, height: 0} when called during render (before layout is calculated). Call it from post-render code, such as useEffect, useLayoutEffect, input handlers, or timer callbacks. When content changes, pass the relevant dependency to your effect so it re-measures after each update.
ref
Type: MutableRef
A reference to a <Box> element captured with the ref property.
See Refs for more information on how to capture references.
Ink supports React Devtools out of the box. To enable integration with React Devtools in your Ink-based CLI, first ensure you have installed the optional react-devtools-core dependency, and then run your app with the DEV=true environment variable:
DEV=true my-cli
Then, start React Devtools itself:
npx react-devtools
After it starts, you should see the component tree of your CLI.
You can even inspect and change the props of components, and see the results immediately in the CLI, without restarting it.
[!NOTE]
You must manually quit your CLI via Ctrl+C after you’re done testing.
Screen Reader Support
Ink has basic support for screen readers.
To enable it, you can either pass the isScreenReaderEnabled option to the render function or set the INK_SCREEN_READER environment variable to true.
Ink implements a small subset of functionality from the ARIA specification.
render(<MyApp />, {isScreenReaderEnabled: true});
When screen reader support is enabled, Ink will try its best to generate a screen-reader-friendly output.
For example, for this code:
<Box aria-role="checkbox" aria-state={{checked: true}}>
<Text>Accept terms and conditions</Text>
</Box>
Ink will generate the following output for screen readers:
(checked) checkbox: Accept terms and conditions
You can also provide a custom label for screen readers if you want to render something different for them.
For example, if you are building a progress bar, you can use aria-label to provide a more descriptive label for screen readers.
In the example above, the screen reader will read “Progress: 50%” instead of “50%”.
aria-label
Type: string
A label for the element for screen readers.
aria-hidden
Type: boolean Default: false
Hide the element from screen readers.
aria-role
Type: string
The role of the element.
Supported values:
button
checkbox
radio
radiogroup
list
listitem
menu
menuitem
progressbar
tab
tablist
timer
toolbar
table
aria-state
Type: object
The state of the element.
Supported values:
checked (boolean)
disabled (boolean)
expanded (boolean)
selected (boolean)
Creating Components
When building custom components, it’s important to keep accessibility in mind. While Ink provides the building blocks, ensuring your components are accessible will make your CLIs usable by a wider audience.
General Principles
Provide screen reader-friendly output: Use the useIsScreenReaderEnabled hook to detect if a screen reader is active. You can then render more descriptive output for screen reader users.
Leverage ARIA props: For components that have a specific role (e.g., a checkbox or button), use the aria-role, aria-state, and aria-label props on <Box> and <Text> to provide semantic meaning to screen readers.
For a practical example of building an accessible component, see the ARIA example.
Write to stdout - Write to stdout, bypassing main Ink output.
Write to stderr - Write to stderr, bypassing main Ink output.
Static - Use the <Static> component to render permanent output.
Child process - Renders output from a child process.
Router - Navigate between routes using React Router’s MemoryRouter.
Continuous Integration
When running on CI (detected via the CI environment variable), Ink adapts its rendering:
Only the last frame is rendered on exit, instead of continuously updating the terminal. This is because most CI environments don’t support the ANSI escape sequences used to overwrite previous output.
Terminal resize events are not listened to.
If your CI environment supports full terminal rendering and you want to opt out of this behavior, set CI=false:
Ink provides the same component-based UI building experience that React offers in the browser, but for command-line apps. It uses Yoga to build Flexbox layouts in the terminal, so most CSS-like properties are available in Ink as well. If you are already familiar with React, you already know Ink.
Since Ink is a React renderer, all features of React are supported. Head over to the React website for documentation on how to use it. Only Ink’s methods are documented in this readme.
My open source work is supported by the community ❤️
Install
Usage
Who’s Using Ink?
kyt- a toolkit that encapsulates and manages the configuration for web apps.node_modulesdirectories to free up disk space.(PRs welcome. Append new entries at the end. Repos must have 100+ stars and showcase Ink beyond a basic list picker.)
Contents
<Text><Box><Newline><Spacer><Static><Transform>useInputusePasteuseAppuseStdinuseStdoutuseBoxMetricsuseStderruseWindowSizeuseFocususeFocusManageruseCursorGetting Started
Use create-ink-app to quickly scaffold a new Ink-based CLI.
Alternatively, create a TypeScript project:
Manual JavaScript setup
Ink requires the same Babel setup as you would do for regular React-based apps in the browser.
Set up Babel with a React preset to ensure all examples in this readme work as expected. After installing Babel, install
@babel/preset-reactand insert the following configuration inbabel.config.json:Next, create a file
source.js, where you’ll type code that uses Ink:Then, transpile this file with Babel:
Now you can run
cli.jswith Node.js:If you don’t like transpiling files during development, you can use import-jsx or @esbuild-kit/esm-loader to
importa JSX file and transpile it on the fly.Ink uses Yoga, a Flexbox layout engine, to build great user interfaces for your CLIs using familiar CSS-like properties you’ve used when building apps for the browser. It’s important to remember that each element is a Flexbox container. Think of it as if every
<div>in the browser haddisplay: flex. See<Box>built-in component below for documentation on how to use Flexbox layouts in Ink. Note that all text must be wrapped in a<Text>component.App Lifecycle
An Ink app is a Node.js process, so it stays alive only while there is active work in the event loop (timers, pending promises,
useInputlistening onstdin, etc.). If your component tree has no async work, the app will render once and exit immediately.To exit the app, press Ctrl+C (enabled by default via
exitOnCtrlC), callexit()fromuseAppinside a component, or callunmount()on the object returned byrender().Use
waitUntilExit()to run code after the app is unmounted:Components
<Text>This component can display text and change its style to make it bold, underlined, italic, or strikethrough.
color
Type:
stringChange text color. Ink uses chalk under the hood, so all its functionality is supported.
backgroundColor
Type:
stringSame as
colorabove, but for background.dimColor
Type:
booleanDefault:
falseDim the color (make it less bright).
bold
Type:
booleanDefault:
falseMake the text bold.
italic
Type:
booleanDefault:
falseMake the text italic.
underline
Type:
booleanDefault:
falseMake the text underlined.
strikethrough
Type:
booleanDefault:
falseMake the text crossed with a line.
inverse
Type:
booleanDefault:
falseInvert background and foreground colors.
wrap
Type:
stringAllowed values:
wraptruncatetruncate-starttruncate-middletruncate-endDefault:
wrapThis property tells Ink to wrap or truncate text if its width is larger than the container. If
wrapis passed (the default), Ink will wrap text and split it into multiple lines. Iftruncate-*is passed, Ink will truncate text instead, resulting in one line of text with the rest cut off.<Box><Box>is an essential Ink component to build your layout. It’s like<div style="display: flex">in the browser.Dimensions
width
Type:
numberstringWidth of the element in spaces. You can also set it as a percentage, which will calculate the width based on the width of the parent element.
height
Type:
numberstringHeight of the element in lines (rows). You can also set it as a percentage, which will calculate the height based on the height of the parent element.
minWidth
Type:
numberSets a minimum width of the element. Percentages aren’t supported yet; see https://github.com/facebook/yoga/issues/872.
minHeight
Type:
numberstringSets a minimum height of the element in lines (rows). You can also set it as a percentage, which will calculate the minimum height based on the height of the parent element.
maxWidth
Type:
numberSets a maximum width of the element. Percentages aren’t supported yet; see https://github.com/facebook/yoga/issues/872.
maxHeight
Type:
numberstringSets a maximum height of the element in lines (rows). You can also set it as a percentage, which will calculate the maximum height based on the height of the parent element.
aspectRatio
Type:
numberDefines the aspect ratio (width/height) for the element.
Use it with at least one size constraint (
width,height,minHeight, ormaxHeight) so Ink can derive the missing dimension.Padding
paddingTop
Type:
numberDefault:
0Top padding.
paddingBottom
Type:
numberDefault:
0Bottom padding.
paddingLeft
Type:
numberDefault:
0Left padding.
paddingRight
Type:
numberDefault:
0Right padding.
paddingX
Type:
numberDefault:
0Horizontal padding. Equivalent to setting
paddingLeftandpaddingRight.paddingY
Type:
numberDefault:
0Vertical padding. Equivalent to setting
paddingTopandpaddingBottom.padding
Type:
numberDefault:
0Padding on all sides. Equivalent to setting
paddingTop,paddingBottom,paddingLeftandpaddingRight.Margin
marginTop
Type:
numberDefault:
0Top margin.
marginBottom
Type:
numberDefault:
0Bottom margin.
marginLeft
Type:
numberDefault:
0Left margin.
marginRight
Type:
numberDefault:
0Right margin.
marginX
Type:
numberDefault:
0Horizontal margin. Equivalent to setting
marginLeftandmarginRight.marginY
Type:
numberDefault:
0Vertical margin. Equivalent to setting
marginTopandmarginBottom.margin
Type:
numberDefault:
0Margin on all sides. Equivalent to setting
marginTop,marginBottom,marginLeftandmarginRight.Gap
gap
Type:
numberDefault:
0Size of the gap between an element’s columns and rows. A shorthand for
columnGapandrowGap.columnGap
Type:
numberDefault:
0Size of the gap between an element’s columns.
rowGap
Type:
numberDefault:
0Size of the gap between an element’s rows.
Flex
flexGrow
Type:
numberDefault:
0See flex-grow.
flexShrink
Type:
numberDefault:
1See flex-shrink.
flexBasis
Type:
numberstringSee flex-basis.
flexDirection
Type:
stringAllowed values:
rowrow-reversecolumncolumn-reverseSee flex-direction.
flexWrap
Type:
stringAllowed values:
nowrapwrapwrap-reverseSee flex-wrap.
alignItems
Type:
stringAllowed values:
flex-startcenterflex-endstretchbaselineSee align-items.
alignSelf
Type:
stringDefault:
autoAllowed values:
autoflex-startcenterflex-endstretchbaselineSee align-self.
alignContent
Type:
stringDefault:
flex-startAllowed values:
flex-startflex-endcenterstretchspace-betweenspace-aroundspace-evenlyDefines alignment between flex lines on the cross axis when
flexWrapcreates multiple lines. See align-content. Unlike CSS (stretch), Ink defaults toflex-startso wrapped lines stay compact and fixed-height boxes don’t gain unexpected empty rows unless you opt in to stretching.justifyContent
Type:
stringAllowed values:
flex-startcenterflex-endspace-betweenspace-aroundspace-evenlySee justify-content.
Position
position
Type:
stringAllowed values:
relativeabsolutestaticDefault:
relativeControls how the element is positioned.
When
positionisstatic,top,right,bottom, andleftare ignored.top
Type:
numberstringTop offset for positioned elements. You can also set it as a percentage of the parent size.
right
Type:
numberstringRight offset for positioned elements. You can also set it as a percentage of the parent size.
bottom
Type:
numberstringBottom offset for positioned elements. You can also set it as a percentage of the parent size.
left
Type:
numberstringLeft offset for positioned elements. You can also set it as a percentage of the parent size.
Visibility
display
Type:
stringAllowed values:
flexnoneDefault:
flexSet this property to
noneto hide the element.overflowX
Type:
stringAllowed values:
visiblehiddenDefault:
visibleBehavior for an element’s overflow in the horizontal direction.
overflowY
Type:
stringAllowed values:
visiblehiddenDefault:
visibleBehavior for an element’s overflow in the vertical direction.
overflow
Type:
stringAllowed values:
visiblehiddenDefault:
visibleA shortcut for setting
overflowXandoverflowYat the same time.Borders
borderStyle
Type:
stringAllowed values:
singledoubleroundboldsingleDoubledoubleSingleclassic|BoxStyleAdd a border with a specified style. If
borderStyleisundefined(the default), no border will be added. Ink uses border styles from thecli-boxesmodule.Alternatively, pass a custom border style like so:
See example in examples/borders.
borderColor
Type:
stringChange border color. A shorthand for setting
borderTopColor,borderRightColor,borderBottomColor, andborderLeftColor.borderTopColor
Type:
stringChange top border color. Accepts the same values as
colorin<Text>component.borderRightColor
Type:
stringChange the right border color. Accepts the same values as
colorin<Text>component.borderBottomColor
Type:
stringChange the bottom border color. Accepts the same values as
colorin<Text>component.borderLeftColor
Type:
stringChange the left border color. Accepts the same values as
colorin<Text>component.borderDimColor
Type:
booleanDefault:
falseDim the border color. A shorthand for setting
borderTopDimColor,borderBottomDimColor,borderLeftDimColor, andborderRightDimColor.borderTopDimColor
Type:
booleanDefault:
falseDim the top border color.
borderBottomDimColor
Type:
booleanDefault:
falseDim the bottom border color.
borderLeftDimColor
Type:
booleanDefault:
falseDim the left border color.
borderRightDimColor
Type:
booleanDefault:
falseDim the right border color.
borderTop
Type:
booleanDefault:
trueDetermines whether the top border is visible.
borderRight
Type:
booleanDefault:
trueDetermines whether the right border is visible.
borderBottom
Type:
booleanDefault:
trueDetermines whether the bottom border is visible.
borderLeft
Type:
booleanDefault:
trueDetermines whether the left border is visible.
Background
backgroundColor
Type:
stringBackground color for the element.
Accepts the same values as
colorin the<Text>component.The background color fills the entire
<Box>area and is inherited by child<Text>components unless they specify their ownbackgroundColor.Background colors work with borders and padding:
See example in examples/box-backgrounds.
<Newline>Adds one or more newline (
\n) characters. Must be used within<Text>components.count
Type:
numberDefault:
1Number of newlines to insert.
Output:
<Spacer>A flexible space that expands along the major axis of its containing layout. It’s useful as a shortcut for filling all the available space between elements.
For example, using
<Spacer>in a<Box>with default flex direction (row) will position “Left” on the left side and will push “Right” to the right side.In a vertical flex direction (
column), it will position “Top” at the top of the container and push “Bottom” to the bottom. Note that the container needs to be tall enough to see this in effect.<Static><Static>component permanently renders its output above everything else. It’s useful for displaying activity like completed tasks or logs - things that don’t change after they’re rendered (hence the name “Static”).It’s preferred to use
<Static>for use cases like these when you can’t know or control the number of items that need to be rendered.For example, Tap uses
<Static>to display a list of completed tests. Gatsby uses it to display a list of generated pages while still displaying a live progress bar.See examples/static for an example usage of
<Static>component.items
Type:
ArrayArray of items of any type to render using the function you pass as a component child.
style
Type:
objectStyles to apply to a container of child elements. See
<Box>for supported properties.children(item)
Type:
FunctionFunction that is called to render every item in the
itemsarray. The first argument is the item itself, and the second argument is the index of that item in theitemsarray.Note that a
keymust be assigned to the root component.<Transform>Transform a string representation of React components before they’re written to output. For example, you might want to apply a gradient to text, add a clickable link, or create some text effects. These use cases can’t accept React nodes as input; they expect a string. That’s what the
<Transform>component does: it gives you an output string of its child components and lets you transform it in any way.Since the
transformfunction converts all characters to uppercase, the final output rendered to the terminal will be “HELLO WORLD”, not “Hello World”.When the output wraps to multiple lines, it can be helpful to know which line is being processed.
For example, to implement a hanging indent component, you can indent all the lines except for the first.
transform(outputLine, index)
Type:
FunctionFunction that transforms children output. It accepts children and must return transformed children as well.
children
Type:
stringOutput of child components.
index
Type:
numberThe zero-indexed line number of the line that’s currently being transformed.
Hooks
useInput(inputHandler, options?)
A React hook that returns
voidand handles user input. It’s a more convenient alternative to usinguseStdinand listening fordataevents. The callback you pass touseInputis called for each character when the user enters any input. However, if the user pastes text and it’s more than one character, the callback will be called only once, and the whole string will be passed asinput. You can find a full example of usinguseInputat examples/use-input.inputHandler(input, key)
Type:
FunctionThe handler function that you pass to
useInputreceives two arguments:input
Type:
stringThe input that the program received.
key
Type:
objectHandy information about a key that was pressed.
key.leftArrow
key.rightArrow
key.upArrow
key.downArrow
Type:
booleanDefault:
falseIf an arrow key was pressed, the corresponding property will be
true. For example, if the user presses the left arrow key,key.leftArrowequalstrue.key.return
Type:
booleanDefault:
falseReturn (Enter) key was pressed.
key.escape
Type:
booleanDefault:
falseEscape key was pressed.
key.ctrl
Type:
booleanDefault:
falseCtrl key was pressed.
key.shift
Type:
booleanDefault:
falseShift key was pressed.
key.tab
Type:
booleanDefault:
falseTab key was pressed.
key.backspace
Type:
booleanDefault:
falseBackspace key was pressed.
key.delete
Type:
booleanDefault:
falseDelete key was pressed.
key.pageDown
key.pageUp
Type:
booleanDefault:
falseIf the Page Up or Page Down key was pressed, the corresponding property will be
true. For example, if the user presses Page Down,key.pageDownequalstrue.key.home
key.end
Type:
booleanDefault:
falseIf the Home or End key was pressed, the corresponding property will be
true. For example, if the user presses End,key.endequalstrue.key.meta
Type:
booleanDefault:
falseMeta key was pressed.
key.super
Type:
booleanDefault:
falseSuper key (Cmd on macOS, Win on Windows) was pressed. Requires kitty keyboard protocol.
key.hyper
Type:
booleanDefault:
falseHyper key was pressed. Requires kitty keyboard protocol.
key.capsLock
Type:
booleanDefault:
falseCaps Lock was active. Requires kitty keyboard protocol.
key.numLock
Type:
booleanDefault:
falseNum Lock was active. Requires kitty keyboard protocol.
key.eventType
Type:
'press' | 'repeat' | 'release'Default:
undefinedThe type of key event. Only available with kitty keyboard protocol. Without the protocol, this property is
undefined.options
Type:
objectisActive
Type:
booleanDefault:
trueEnable or disable capturing of user input. Useful when there are multiple
useInputhooks used at once to avoid handling the same input several times.usePaste(handler, options?)
A React hook that calls
handlerwhenever the user pastes text. Bracketed paste mode (\x1b[?2004h) is automatically enabled while the hook is active, so pasted text arrives as a single string rather than being misinterpreted as individual key presses.usePasteanduseInputcan be used together in the same component. They operate on separate event channels, so paste content is never forwarded touseInputhandlers whenusePasteis active.handler(text)
Type:
FunctionCalled with the full pasted string whenever the user pastes text. The string is delivered verbatim — newlines, escape sequences, and other special characters are preserved exactly as pasted.
text
Type:
stringThe pasted text.
options
Type:
objectisActive
Type:
booleanDefault:
trueEnable or disable the paste handler. Useful when multiple components use
usePasteand only one should be active at a time.useApp()
A React hook that returns app lifecycle methods.
exit(errorOrResult?)
Type:
FunctionExit (unmount) the whole Ink app.
errorOrResult
Type:
Error | unknownOptional value that controls how
waitUntilExitsettles:exit()resolves withundefined.exit(error)rejects whenerroris anError.exit(value)resolves withvalue.waitUntilRenderFlush()
Type:
FunctionReturns a promise that settles after pending render output is flushed to stdout.
useStdin()
A React hook that returns the stdin stream and stdin-related utilities.
stdin
Type:
stream.ReadableDefault:
process.stdinThe stdin stream passed to
render()inoptions.stdin, orprocess.stdinby default. Useful if your app needs to handle user input.isRawModeSupported
Type:
booleanA boolean flag determining if the current
stdinsupportssetRawMode. A component usingsetRawModemight want to useisRawModeSupportedto nicely fall back in environments where raw mode is not supported.setRawMode(isRawModeEnabled)
Type:
functionisRawModeEnabled
Type:
booleanSee
setRawMode. Ink exposes this function to be able to handle Ctrl+C, that’s why you should use Ink’ssetRawModeinstead ofprocess.stdin.setRawMode.Warning: This function will throw unless the current
stdinsupportssetRawMode. UseisRawModeSupportedto detectsetRawModesupport.useStdout()
A React hook that returns the stdout stream where Ink renders your app and stdout-related utilities.
stdout
Type:
stream.WritableDefault:
process.stdoutwrite(data)
Write any string to stdout while preserving Ink’s output. It’s useful when you want to display external information outside of Ink’s rendering and ensure there’s no conflict between the two. It’s similar to
<Static>, except it can’t accept components; it only works with strings.data
Type:
stringData to write to stdout.
See additional usage example in examples/use-stdout.
useBoxMetrics(ref)
A React hook that returns the current layout metrics for a tracked box element. It updates when layout changes (for example terminal resize, sibling/content changes, or position changes).
Use
hasMeasuredto detect when the currently tracked element has been measured.ref
Type:
React.RefObject<DOMElement>A ref to the
<Box>element to track.width
Type:
numberElement width.
height
Type:
numberElement height.
left
Type:
numberDistance from the left edge of the parent.
top
Type:
numberDistance from the top edge of the parent.
hasMeasured
Type:
booleanWhether the currently tracked element has been measured.
useStderr()
A React hook that returns the stderr stream and stderr-related utilities.
stderr
Type:
stream.WritableDefault:
process.stderrStderr stream.
write(data)
Write any string to stderr while preserving Ink’s output.
It’s useful when you want to display external information outside of Ink’s rendering and ensure there’s no conflict between the two. It’s similar to
<Static>, except it can’t accept components; it only works with strings.data
Type:
stringData to write to stderr.
useWindowSize()
A React hook that returns the current terminal dimensions and re-renders the component whenever the terminal is resized.
columns
Type:
numberNumber of columns (horizontal character cells).
rows
Type:
numberNumber of rows (vertical character cells).
useFocus(options?)
A React hook that returns focus state and focus controls for the current component. A component that uses the
useFocushook becomes “focusable” to Ink, so when the user presses Tab, Ink will switch focus to this component. If there are multiple components that execute theuseFocushook, focus will be given to them in the order in which these components are rendered. This hook returns an object with anisFocusedboolean property, which determines whether this component is focused.options
autoFocus
Type:
booleanDefault:
falseAuto-focus this component if there’s no active (focused) component right now.
isActive
Type:
booleanDefault:
trueEnable or disable this component’s focus, while still maintaining its position in the list of focusable components. This is useful for inputs that are temporarily disabled.
id
Type:
stringRequired:
falseSet a component’s focus ID, which can be used to programmatically focus the component. This is useful for large interfaces with many focusable elements to avoid having to cycle through all of them.
See example in examples/use-focus and examples/use-focus-with-id.
useFocusManager()
A React hook that returns methods to manage focus across focusable components.
enableFocus()
Enable focus management for all components.
disableFocus()
Disable focus management for all components. The currently active component (if there’s one) will lose its focus.
focusNext()
Switch focus to the next focusable component. If there’s no active component right now, focus will be given to the first focusable component. If the active component is the last in the list of focusable components, focus will be switched to the first focusable component.
focusPrevious()
Switch focus to the previous focusable component. If there’s no active component right now, focus will be given to the first focusable component. If the active component is the first in the list of focusable components, focus will be switched to the last focusable component.
focus(id)
id
Type:
stringSwitch focus to the component with the given
id. If there’s no component with that ID, focus is not changed.activeId
Type:
string | undefinedThe ID of the currently focused component, or
undefinedif no component is focused.useCursor()
A React hook that returns methods to control the terminal cursor position after each render. This is essential for IME (Input Method Editor) support, where the composing character is displayed at the cursor location.
setCursorPosition(position)
Set the cursor position relative to the Ink output. Pass
undefinedto hide the cursor.position
Type:
object | undefinedUse
string-widthto calculatexfor strings containing wide characters (CJK, emoji).See a full example at examples/cursor-ime.
x
Type:
numberColumn position (0-based).
y
Type:
numberRow position from the top of the Ink output (0 = first line).
useIsScreenReaderEnabled()
A React hook that returns whether a screen reader is enabled. This is useful when you want to render different output for screen readers.
API
render(tree, options?)
Returns:
InstanceMount a component and render the output.
tree
Type:
ReactNodeoptions
Type:
objectstdout
Type:
stream.WritableDefault:
process.stdoutOutput stream where the app will be rendered.
stdin
Type:
stream.ReadableDefault:
process.stdinInput stream where app will listen for input.
stderr
Type:
stream.WritableDefault:
process.stderrError stream.
exitOnCtrlC
Type:
booleanDefault:
trueConfigure whether Ink should listen for Ctrl+C keyboard input and exit the app. This is needed in case
process.stdinis in raw mode, because then Ctrl+C is ignored by default and the process is expected to handle it manually.patchConsole
Type:
booleanDefault:
truePatch console methods to ensure console output doesn’t mix with Ink’s output. When any of the
console.*methods are called (likeconsole.log()), Ink intercepts their output, clears the main output, renders output from the console method, and then rerenders the main output again. That way, both are visible and don’t overlap each other.This functionality is powered by patch-console, so if you need to disable Ink’s interception of output but want to build something custom, you can use that.
onRender
Type:
({renderTime: number}) => voidDefault:
undefinedRuns the given callback after each render and re-render with render metrics. This callback runs after Ink commits a frame, but it does not wait for
stdout/stderrstream callbacks. To run code after output is flushed, usewaitUntilRenderFlush().isScreenReaderEnabled
Type:
booleanDefault:
process.env['INK_SCREEN_READER'] === 'true'Enable screen reader support. See Screen Reader Support.
debug
Type:
booleanDefault:
falseIf
true, each update will be rendered as separate output, without replacing the previous one.maxFps
Type:
numberDefault:
30Maximum frames per second for render updates. This controls how frequently the UI can update to prevent excessive re-rendering. Higher values allow more frequent updates but may impact performance. Setting it to a lower value may be useful for components that update very frequently, to reduce CPU usage.
incrementalRendering
Type:
booleanDefault:
falseEnable incremental rendering mode which only updates changed lines instead of redrawing the entire output. This can reduce flickering and improve performance for frequently updating UIs.
concurrent
Type:
booleanDefault:
falseEnable React Concurrent Rendering mode.
When enabled:
useTransitionanduseDeferredValuehooks are fully functionalinteractive
Type:
booleanDefault:
true(falseif in CI (detected viais-in-ci) orstdout.isTTYis falsy)Override automatic interactive mode detection.
By default, Ink detects whether the environment is interactive based on CI detection and
stdout.isTTY. When non-interactive, Ink skips terminal-specific features like ANSI erase sequences, cursor manipulation, synchronized output, resize handling, and kitty keyboard auto-detection. Only the final frame of non-static output is written at unmount.Most users should not need to set this option. Use it when you have your own “interactive” detection logic that differs from the built-in behavior.
kittyKeyboard
Type:
objectDefault:
undefinedEnable the kitty keyboard protocol for enhanced keyboard input handling. When enabled, terminals that support the protocol will report additional key information including
super,hyper,capsLock,numLockmodifiers andeventType(press/repeat/release).kittyKeyboard.mode
Type:
'auto' | 'enabled' | 'disabled'Default:
'auto''auto': Detect terminal support using a heuristic precheck (known terminals like kitty, WezTerm, Ghostty) followed by a protocol query confirmation (CSI ? u). The protocol is only enabled if the terminal responds to the query within a short timeout.'enabled': Force enable the protocol. Both stdin and stdout must be TTYs.'disabled': Never enable the protocol.kittyKeyboard.flags
Type:
string[]Default:
['disambiguateEscapeCodes']Protocol flags to request from the terminal. Pass an array of flag name strings.
Available flags:
'disambiguateEscapeCodes'- Disambiguate escape codes'reportEventTypes'- Report key press, repeat, and release events'reportAlternateKeys'- Report alternate key encodings'reportAllKeysAsEscapeCodes'- Report all keys as escape codes'reportAssociatedText'- Report associated text with key eventsBehavior notes
When the kitty keyboard protocol is enabled, input handling changes in several ways:
inputparameter ofuseInput. They can still be detected via thekeyobject properties.Ctrl+letteras codepoint 1-26 (the kitty CSI-u alternate form),inputis set to the letter name (e.g.'c'forCtrl+C) andkey.ctrlistrue. This ensuresexitOnCtrlCand customCtrl+letterhandlers continue to work regardless of which codepoint form the terminal uses.Ctrl+IvsTab- without the protocol, both produce the same byte (\x09). With the protocol, they are reported as distinct keys.Shift+EntervsEnter- the shift modifier is correctly reported.Escapekey vsCtrl+[- these are disambiguated.reportEventTypesflag, key press, repeat, and release events are distinguished viakey.eventType.renderToString(tree, options?)
Returns:
stringRender a React element to a string synchronously. Unlike
render(), this function does not write to stdout, does not set up any terminal event listeners, and returns the rendered output as a string.Useful for generating documentation, writing output to files, testing, or any scenario where you need the rendered output as a string without starting a persistent terminal application.
Notes:
useInput,useStdin,useStdout,useStderr,useWindowSize,useApp,useFocus,useFocusManager) return default no-op values since there is no terminal session. They will not throw, but they will not function as in a live terminal.useEffectcallbacks will execute during rendering (due to synchronous rendering mode), but state updates they trigger will not affect the returned output, which reflects the initial render.useLayoutEffectcallbacks fire synchronously during commit, so state updates they trigger will be reflected in the output.<Static>component is supported — its output is prepended to the dynamic output.tree
Type:
ReactNodeoptions
Type:
objectcolumns
Type:
numberDefault:
80Width of the virtual terminal in columns. Controls where text wrapping occurs.
Instance
This is the object that
render()returns.rerender(tree)
Replace the previous root node with a new one or update the props of the current root node.
tree
Type:
ReactNodeunmount()
Manually unmount the whole Ink app.
waitUntilExit()
Returns a promise that settles when the app is unmounted.
It resolves with the value passed to
exit(value)and rejects with the error passed toexit(error). Whenunmount()is called manually, it settles after unmount-related stdout writes complete.waitUntilRenderFlush()
Returns a promise that settles after pending render output is flushed to stdout.
Useful when you need to run code only after a frame is written:
cleanup()
Delete the internal Ink instance associated with the current
stdout. This is mostly useful for advanced cases (for example, tests) where you needrender()to create a fresh instance for the same stream. This does not unmount the current app.clear()
Clear output.
measureElement(ref)
Measure the dimensions of a particular
<Box>element. Returns an object withwidthandheightproperties. This function is useful when your component needs to know the amount of available space it has. You can use it when you need to change the layout based on the length of its content.ref
Type:
MutableRefA reference to a
<Box>element captured with therefproperty. See Refs for more information on how to capture references.Testing
Ink components are simple to test with ink-testing-library. Here’s a simple example that checks how the component is rendered:
Check out ink-testing-library for more examples and full documentation.
Using React Devtools
Ink supports React Devtools out of the box. To enable integration with React Devtools in your Ink-based CLI, first ensure you have installed the optional
react-devtools-coredependency, and then run your app with theDEV=trueenvironment variable:Then, start React Devtools itself:
After it starts, you should see the component tree of your CLI. You can even inspect and change the props of components, and see the results immediately in the CLI, without restarting it.
Screen Reader Support
Ink has basic support for screen readers.
To enable it, you can either pass the
isScreenReaderEnabledoption to therenderfunction or set theINK_SCREEN_READERenvironment variable totrue.Ink implements a small subset of functionality from the ARIA specification.
When screen reader support is enabled, Ink will try its best to generate a screen-reader-friendly output.
For example, for this code:
Ink will generate the following output for screen readers:
You can also provide a custom label for screen readers if you want to render something different for them.
For example, if you are building a progress bar, you can use
aria-labelto provide a more descriptive label for screen readers.In the example above, the screen reader will read “Progress: 50%” instead of “50%”.
aria-labelType:
stringA label for the element for screen readers.
aria-hiddenType:
booleanDefault:
falseHide the element from screen readers.
aria-role
Type:
stringThe role of the element.
Supported values:
buttoncheckboxradioradiogrouplistlistitemmenumenuitemprogressbartabtablisttimertoolbartablearia-state
Type:
objectThe state of the element.
Supported values:
checked(boolean)disabled(boolean)expanded(boolean)selected(boolean)Creating Components
When building custom components, it’s important to keep accessibility in mind. While Ink provides the building blocks, ensuring your components are accessible will make your CLIs usable by a wider audience.
General Principles
useIsScreenReaderEnabledhook to detect if a screen reader is active. You can then render more descriptive output for screen reader users.aria-role,aria-state, andaria-labelprops on<Box>and<Text>to provide semantic meaning to screen readers.For a practical example of building an accessible component, see the ARIA example.
Useful Components
Useful Hooks
Recipes
MemoryRouter.Examples
The
examplesdirectory contains a set of real examples. You can run them with:<Box>component.useFocushook to manage focus between components.<Static>component to render permanent output.MemoryRouter.Continuous Integration
When running on CI (detected via the
CIenvironment variable), Ink adapts its rendering:If your CI environment supports full terminal rendering and you want to opt out of this behavior, set
CI=false:Maintainers