Github url

ink

by vadimdemedes

vadimdemedes /ink

🌈 React for interactive command-line apps

13.5K Stars 345 Forks Last release: 5 months ago (v2.7.1) MIT License 424 Commits 52 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

Ink

React for CLIs. Build and test your CLI output using components.

Build Statusnpm

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 props are available in Ink as well. If you are already familiar with React, you already know Ink.

Since Ink is a React renderer, it means that all features of React are supported. Head over to React website for documentation on how to use it. Only Ink's methods will be documented in this readme.

Note: This is documentation for Ink 3, which is unreleased yet. If you're looking for docs on Ink 2, check out this release. There's also a migration guide from Ink 2 available.

Install

$ npm install ink react

Usage

import React, {useState, useEffect} from 'react'; import {render, Text} from 'ink'; const Counter = () =\> { const [counter, setCounter] = useState(0); useEffect(() =\> { const timer = setInterval(() =\> { setCounter(previousCounter =\> previousCounter + 1); }, 100); return () =\> { clearInterval(timer); }; }, []); return {counter} tests passed; }; render(<counter></counter>);

You can also check it out live on repl.it sandbox. Feel free to play around with the code and fork this repl at https://repl.it/@vadimdemedes/ink-counter-demo.

Who's Using Ink?

  • Gatsby - Gatsby is a modern web framework for blazing fast websites.
  • Parcel - Blazing fast, zero configuration web application bundler.
  • tap - A Test-Anything-Protocol library for JavaScript.
  • Yarn 2 - Fast, reliable, and secure dependency management for JavaScript.
  • Typewriter - Generates strongly-typed Segment analytics clients from arbitrary JSON Schema.
  • Prisma - The unified data layer for modern applications.
  • Wallace - Pretty CSS analytics on the CLI.
  • Blitz - The Fullstack React Framework.
  • New York Times - NYT uses Ink
    kyt
    • a toolkit that encapsulates and manages the configuration for web apps.
  • tink - Next-generation runtime and package manager.
  • loki - Visual Regression Testing for Storybook.
  • Bit - Build, distribute and collaborate on components.
  • Remirror - Your friendly, world-class editor toolkit.
  • Prime CSS - Open Source GraphQL CMS.
  • Splash - Observe the splash zone of a change across the Shopify's Polaris component library.
  • emoj - Find relevant emoji on the command-line.
  • emma - Terminal assistant to find and install npm packages.
  • sindresorhus - The Sindre Sorhus CLI.
  • swiff - Multi-environment command line tools for time-saving web developers.
  • share - Quickly share files from your command line.
  • Kubelive - CLI for Kubernetes to provide live data about the cluster and its resources.
  • changelog-view - Tool view changelog in console.
  • gomoku-terminal - Play online Gomoku in the terminal.
  • cfpush - An interactive Cloud Foundry tutorial in your terminal.
  • startd - Turn your React component into a web app from the command-line.
  • wiki-cli - Search Wikipedia and read summaries directly in your terminal.
  • garson - Build interactive config-based command-line interfaces.

Contents

](https://github.com/vadimdemedes/ink/blob/master/#text)
  - [

](https://github.com/vadimdemedes/ink/blob/master/#box)
  - [

](https://github.com/vadimdemedes/ink/blob/master/#newline)
  - [

](https://github.com/vadimdemedes/ink/blob/master/#spacer)
  - [

](https://github.com/vadimdemedes/ink/blob/master/#static)
  - [

](https://github.com/vadimdemedes/ink/blob/master/#transform)
- [Hooks](https://github.com/vadimdemedes/ink/blob/master/#hooks)
  - [

useInput

](https://github.com/vadimdemedes/ink/blob/master/#useinputinputhandler-options)
  - [

useApp

](https://github.com/vadimdemedes/ink/blob/master/#useapp)
  - [

useStdin

](https://github.com/vadimdemedes/ink/blob/master/#usestdin)
  - [

useStdout

](https://github.com/vadimdemedes/ink/blob/master/#usestdout)
  - [

useStderr

](https://github.com/vadimdemedes/ink/blob/master/#usestderr)
  - [

useFocus

](https://github.com/vadimdemedes/ink/blob/master/#usefocusoptions)
  - [

useFocusManager

](https://github.com/vadimdemedes/ink/blob/master/#usefocusmanager)
- [API](https://github.com/vadimdemedes/ink/blob/master/#api)
- [Testing](https://github.com/vadimdemedes/ink/blob/master/#testing)
- [Using React Devtools](https://github.com/vadimdemedes/ink/blob/master/#using-react-devtools)
- [Useful Components](https://github.com/vadimdemedes/ink/blob/master/#useful-components)
- [Useful Hooks](https://github.com/vadimdemedes/ink/blob/master/#useful-hooks)
- [Examples](https://github.com/vadimdemedes/ink/blob/master/#examples)

## Getting Started

Use [create-ink-app](https://github.com/vadimdemedes/create-ink-app) to quickly scaffold a new Ink-based CLI.

$ mkdir my-ink-cli $ cd my-ink-cli $ npx create-ink-app

<details><summary>Manual setup</summary>
<p>
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](https://babeljs.io/docs/en/usage), install `@babel/preset-react` and insert the following configuration in `babel.config.json`:

$ npm install --save-dev @babel/preset-react


```json
{
    "presets": [
        "@babel/preset-react",
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": true
                }
            }
        ]
    ]
}

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 = () =&gt; <text>Hello World</text>;

render(<demo></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 to require() 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 props 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 each

in the browser had 

display: flex

. See [

](https://github.com/vadimdemedes/ink/blob/master/#box) built-in component below for documentation on how to use Flexbox layouts in Ink. Note that all text must be wrapped in a [
](https://github.com/vadimdemedes/ink/blob/master/#text) component.
## Components

### 

This component can display text, and change its style to make it bold, underline, italic or strikethrough.

import {render, Text} from 'ink'; const Example = () => ( <> I am green I am black on white I am whiteI am boldI am italicI am underlineI am strikethrough > ); render();


#### color

Type:

string


Change text color. Ink uses [chalk](https://github.com/chalk/chalk) under the hood, so all its functionality is supported.

GreenBlueRed


![](https://github.com/vadimdemedes/ink/raw/master/media/text-color.jpg)

#### backgroundColor

Type:

string


Same as

color

 above, but for background.

GreenBlueRed


![](https://github.com/vadimdemedes/ink/raw/master/media/text-backgroundColor.jpg)

#### dimColor

Type:

boolean

\ Default: 

false


Dim the color (emit a small amount of light).

Dimmed Red


![](https://github.com/vadimdemedes/ink/raw/master/media/text-dimColor.jpg)

#### bold

Type:

boolean

\ Default: 

false


Make the text bold.

#### italic

Type:

boolean

\ Default: 

false


Make the text italic.

#### underline

Type:

boolean

\ Default: 

false


Make the text underlined.

#### strikethrough

Type:

boolean

\ Default: 

false


Make the text crossed with a line.

#### wrap

Type:

string

\ Allowed values: 

wrap

truncate

truncate-start

truncate-middle

truncate-end

\ Default: 

wrap


This property tells Ink to wrap or truncate text if its width is larger than container. If

wrap

 is passed (by default), Ink will wrap text and split it into multiple lines. If 

truncate-*

 is passed, Ink will truncate text instead, which will result in one line of text with the rest cut off.
Hello World //=\> 'Hello\nWorld' // `truncate` is an alias to `truncate-end` Hello World //=\> 'Hello…' Hello World //=\> 'He…ld' Hello World //=\> '…World' ```

<box></box>
<box></box>

is an essential Ink component to build your layout. It's like

in the browser.

import {render, Box, Text} from 'ink'; const Example = () => { This is a box with margin ; }; render();


#### Dimensions

##### width

Type:

number

string


Width of the element in spaces. You can also set it in percent, which will calculate the width based on the width of parent element.
X //=\> 'X ' ```
<box width="{10}">
    <box width="50%">
        <text>X</text>
    </box>
    <text>Y</text>
</box>//=\> 'X Y'
height

Type:

number
string

Height of the element in lines (rows). You can also set it in percent, which will calculate the height based on the height of parent element.

<box height="{4}">
    <text>X</text>
</box>//=\> 'X\n\n\n'
<box height="{6}" flexdirection="column">
    <box height="50%">
        <text>X</text>
    </box>
    <text>Y</text>
</box>//=\> 'X\n\n\nY\n\n'
minWidth

Type:

number

Sets a minimum width of the element. Percentages aren't supported yet, see https://github.com/facebook/yoga/issues/872.

minHeight

Type:

number

Sets a minimum height of the element. Percentages aren't supported yet, see https://github.com/facebook/yoga/issues/872.

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}">Top</box><box paddingbottom="{2}">Bottom</box><box paddingleft="{2}">Left</box><box paddingright="{2}">Right</box><box paddingx="{2}">Left and right</box><box paddingy="{2}">Top and bottom</box><box padding="{2}">Top, bottom, left and right</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}">Top</box><box marginbottom="{2}">Bottom</box><box marginleft="{2}">Left</box><box marginright="{2}">Right</box><box marginx="{2}">Left and right</box><box marginy="{2}">Top and bottom</box><box margin="{2}">Top, bottom, left and right</box>

Flex

flexGrow

Type:

number

\ Default:

0

See flex-grow.

<box>
    <text>Label:</text>
    <box flexgrow="{1}">
        <text>Fills all remaining space</text>
    </box>
</box>
flexShrink

Type:

number

\ Default:

1

See flex-shrink.

<box width="{20}">
    <box flexshrink="{2}" width="{10}">
        <text>Will be 1/4</text>
    </box>
    <box width="{10}">
        <text>Will be 3/4</text>
    </box>
</box>
flexBasis

Type:

number
string

See flex-basis.

<box width="{6}">
    <box flexbasis="{3}">
        <text>X</text>
    </box>
    <text>Y</text>
</box>//=\> 'X Y'
<box width="{6}">
    <box flexbasis="50%">
        <text>X</text>
    </box>
    <text>Y</text>
</box>//=\> 'X Y'
flexDirection

Type:

string

\ Allowed values:

row
row-reverse
column
column-reverse

See flex-direction.

<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
alignItems

Type:

string

\ Allowed values:

flex-start
center
flex-end

See align-items.

<box alignitems="flex-start">
    <box marginright="{1}">
        <text>X</text>
    </box>
    <text>
        A
        <newline></newline>
        B
        <newline></newline>
        C
    </text>
</box>// X A // B // C<box alignitems="center">
    <box marginright="{1}">
        <text>X</text>
    </box>
    <text>
        A
        <newline></newline>
        B
        <newline></newline>
        C
    </text>
</box>// A // X B // C<box alignitems="flex-end">
    <box marginright="{1}">
        <text>X</text>
    </box>
    <text>
        A
        <newline></newline>
        B
        <newline></newline>
        C
    </text>
</box>// A // B // X C
alignSelf

Type:

string

\ Default:

auto

\ Allowed vales:

auto
flex-start
center
flex-end

See align-self.

<box height="{3}">
    <box alignself="flex-start">
        <text>X</text>
    </box>
</box>// X // //<box height="{3}">
    <box alignself="center">
        <text>X</text>
    </box>
</box>// // X //<box height="{3}">
    <box alignself="flex-end">
        <text>X</text>
    </box>
</box>// // // X
justifyContent

Type:

string

\ Allowed values:

flex-start
center
flex-end
space-between
space-around

See justify-content.

<box justifycontent="flex-start">
    <text>X</text>
</box>// [X]<box justifycontent="center">
    <text>X</text>
</box>// [X]<box justifycontent="flex-end">
    <text>X</text>
</box>// [X]<box justifycontent="space-between">
    <text>X</text>
    <text>Y</text>
</box>// [X Y]<box justifycontent="space-around">
    <text>X</text>
    <text>Y</text>
</box>// [X Y]

Visibility

display

Type:

string

\ Allowed values:

flex
none

\ Default:

flex

Set this property to

none

to hide the element.

Borders

borderStyle

Type:

string

\ Allowed values:

single
double
round
bold
singleDouble
doubleSingle
classic

Add a border with a specified style. If

borderStyle

is

undefined

(which it is by default), no border will be added. Ink uses border styles from [

cli-boxes

](https://github.com/sindresorhus/cli-boxes) module.

<box flexdirection="column">
    <box>
        <box borderstyle="single" marginright="{2}">
            <text>single</text>
        </box>

        <box borderstyle="double" marginright="{2}">
            <text>double</text>
        </box>

        <box borderstyle="round" marginright="{2}">
            <text>round</text>
        </box>

        <box borderstyle="bold">
            <text>bold</text>
        </box>
    </box>

    <box margintop="{1}">
        <box borderstyle="singleDouble" marginright="{2}">
            <text>singleDouble</text>
        </box>

        <box borderstyle="doubleSingle" marginright="{2}">
            <text>doubleSingle</text>
        </box>

        <box borderstyle="classic">
            <text>classic</text>
        </box>
    </box>
</box>

See example in examples/borders.

borderColor

Type:

string

Change border color. Accepts the same values as [

color

](https://github.com/vadimdemedes/ink/blob/master/#color) in

component.

<box borderstyle="round" bordercolor="green">
    <text>Green Rounded Box</text>
</box>

<newline></newline>

Adds one or more newline (

\n

) characters. Must be used within

components.

count

Type:

number

\ Default:

1

Number of newlines to insert.

import {render, Text, Newline} from 'ink'; const Example = () =\> ( Hello World ); render(<example></example>);

Output:

Hello World

<spacer></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 spaces between elements.

For example, using

<spacer></spacer>

in a

<box></box>

with default flex direction (

row

) will position "Left" on the left side and will push "Right" to the right side.

import {render, Box, Text, Spacer} from 'ink'; const Example = () =\> ( <box>
        <text>Left</text>
        <spacer></spacer>
        <text>Right</text>
    </box>); render(<example></example>);

In a vertical flex direction (

column

), it will position "Top" to the top of the container and push "Bottom" to the bottom of it. Note, that container needs to be tall to enough to see this in effect.

import {render, Box, Text, Spacer} from 'ink'; const Example = () =\> ( <box flexdirection="column" height="{10}">
        <text>Top</text>
        <spacer></spacer>
        <text>Bottom</text>
    </box>); render(<example></example>);

<static></static>
<static></static>

component permanently renders its output above everything else. It's useful for displaying activity like completed tasks or logs - things that are not changing after they're rendered (hence the name "Static").

It's preferred to use

<static></static>

for use cases like these, when you can't know or control the amount of items that need to be rendered.

For example, Tap uses

<static></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}` }]); setTimeout(run, 100); } }; run(); return () =\> { clearTimeout(timer); }; }, []); return ( \<\> {/\* This part will be rendered once to the terminal \*/} <static items="{tests}">
                {test =&gt; (
                    <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></example>);

Note:

<static></static>

only renders new items in

items

prop and ignores items that were previously rendered. This means that when you add new items to

items

array, changes you make to previous items will not trigger a rerender.

See examples/static for an example usage of

<static></static>

component.

items

Type:

Array

Array of items of any type to render using a function you pass as a component child.

style

Type:

object

Styles to apply to a container of child elements. See [

<box></box>

](https://github.com/vadimdemedes/ink/blob/master/#box) for supported properties.

<static items="{...}" style="{{padding:">
    {...}
</static>

children(item)

Type:

Function

Function that is called to render every item in

items

array. First argument is an item itself and second argument is index of that item in

items

array.

Note that

key

must be assigned to the root component.

<static items="{['a',">
    {(item, index) =&gt; {
        // 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>

Transform a string representation of React components before they are 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 are expecting a string. That's what

<transform></transform>

component does, it gives you an output string of its child components and lets you transform it in any way.

Note:

<transform></transform>

must be applied only to

children components and shouldn't change the dimensions of the output, otherwise layout will be incorrect.

import {render, Transform} from 'ink'; const Example = () =\> ( <transform transform="{output"> output.toUpperCase()}&gt;
        <text>Hello World</text>
    </transform>); render(<example></example>);

Since

transform

function converts all characters to upper case, final output that's rendered to the terminal will be "HELLO WORLD", not "Hello World".

transform(children)

Type:

Function

Function which transforms children output. It accepts children and must return transformed children too.

children

Type:

string

Output of child components.

Hooks

useInput(inputHandler, options?)

This hook is used for handling user input. It's a more convienient alternative to using

useStdin

and listening to

data

events. The callback you pass to

useInput

is called for each character when user enters any input. However, if 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 user presses 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.meta

Type:

boolean

\ Default:

false

Meta key was pressed.

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.

useApp()

useApp

is a React hook, which exposes a method to manually exit the app (unmount).

exit(error?)

Type:

Function

Exit (unmount) the whole Ink app.

error

Type:

Error

Optional error. If passed, [

waitUntilExit

](https://github.com/vadimdemedes/ink/blob/master/waituntilexit) will reject with that error.

import {useApp} from 'ink'; const Example = () =\> { const {exit} = useApp(); // Exit the app after 5 seconds useEffect(() =\> { setTimeout(() =\> { exit(); }, 5000); }, []); return … };

useStdin()

useStdin

is a React hook, which exposes stdin stream.

stdin

Type:

stream.Readable

\ Default:

process.stdin

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.

import {useStdin} from 'ink'; const Example = () =\> { const {isRawModeSupported} = useStdin(); return isRawModeSupported ? ( <myinputcomponent></myinputcomponent> ) : ( <mycomponentthatdoesntuseinput></mycomponentthatdoesntuseinput> ); };

setRawMode(isRawModeEnabled)

Type:

function
isRawModeEnabled

Type:

boolean

See [

setRawMode

](https://nodejs.org/api/tty.html#tty_readstream_setrawmode_mode). Ink exposes this function to be able to handle Ctrl+C, that's why you should use Ink's

setRawMode

instead of

process.stdin.setRawMode

.

Warning: This function will throw unless the current

stdin

supports

setRawMode

. Use [

isRawModeSupported

](https://github.com/vadimdemedes/ink/blob/master/#israwmodesupported) to detect

setRawMode

support.

import {useStdin} from 'ink'; const Example = () =\> { const {setRawMode} = useStdin(); useEffect(() =\> { setRawMode(true); return () =\> { setRawMode(false); }; }); return … };

useStdout()

useStdout

is a React hook, which exposes stdout stream, where Ink renders your app.

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 some external information outside of Ink's rendering and ensure there's no conflict between the two. It's similar to

<static></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 … };

See additional usage example in examples/use-stdout.

useStderr()

useStderr

is a React hook, which exposes stderr stream.

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 some external information outside of Ink's rendering and ensure there's no conflict between the two. It's similar to

<static></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 … };

useFocus(options?)

Component that uses

useFocus

hook becomes "focusable" to Ink, so when user presses Tab, Ink will switch focus to this component. If there are multiple components that execute

useFocus

hook, focus will be given to them in the order that these components are rendered in. This hook returns an object with

isFocused

boolean property, which determines if this component is focused or not.

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.

import {render, useFocus, Text} from 'ink'; const Example = () =\> { const {isFocused} = useFocus(); return {isFocused ? 'I am focused' : 'I am not focused'}; }; render(<example></example>);

See example in examples/use-focus.

useFocusManager()

This hook exposes methods to enable or disable focus management for all components or manually switch focus to next or previous components.

enableFocus()

Enable focus management for all components.

Note: You don't need to call this method manually, unless you've disabled focus management. Focus management is enabled by default.

import {useFocusManager} from 'ink'; const Example = () =\> { const {enableFocus} = useFocusManager(); useEffect(() =\> { enableFocus(); }, []); return … };

disableFocus()

Disable focus management for all components. Currently active component (if there's one) will lose its focus.

import {useFocusManager} from 'ink'; const Example = () =\> { const {disableFocus} = useFocusManager(); useEffect(() =\> { disableFocus(); }, []); return … };

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 active component is the last in the list of focusable components, focus will be switched to the first component.

Note: Ink calls this method when user presses Tab.

import {useFocusManager} from 'ink'; const Example = () =\> { const {focusNext} = useFocusManager(); useEffect(() =\> { focusNext(); }, []); return … };

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 active component is the first in the list of focusable components, focus will be switched to the last component.

Note: Ink calls this method when user presses Shift+Tab.

import {useFocusManager} from 'ink'; const Example = () =\> { const {focusPrevious} = useFocusManager(); useEffect(() =\> { focusPrevious(); }, []); return … };

API

render(tree, options?)

Returns: [

Instance

](https://github.com/vadimdemedes/ink/blob/master/#instance)

Mount a component and render the output.

tree

Type:

ReactElement
options

Type:

object
stdout

Type:

stream.Writable

\ Default:

process.stdout

Output stream where app will be rendered.

stdin

Type:

stream.Readable

\ Default:

process.stdin

Input stream where app will listen for input.

exitOnCtrlC

Type:

boolean

\ Default:

true

Configure whether Ink should listen to 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 process is expected to handle it manually.

patchConsole

Type:

boolean

\ Default:

true

Patch console methods to ensure console output doesn't mix with Ink output. When any of

console.\*

methods are called (like

console.log()

), Ink intercepts their output, clears main output, renders output from the console method and then rerenders main output again. That way both are visible and are not overlapping 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 it.

debug

Type:

boolean

\ Default:

false

If

true

, each update will be rendered as a separate output, without replacing the previous one.

Instance

This is the object that

render()

returns.

rerender(tree)

Replace previous root node with a new one or update props of the current root node.

tree

Type:

ReactElement
// Update props of the root node const {rerender} = render(<counter count="{1}"></counter>); rerender(<counter count="{2}"></counter>); // Replace root node const {rerender} = render(<oldcounter></oldcounter>); rerender(<newcounter></newcounter>);
unmount()

Manually unmount the whole Ink app.

const {unmount} = render(<myapp></myapp>); unmount();
waitUntilExit()

Returns a promise, which resolves when app is unmounted.

const {unmount, waitUntilExit} = render(<myapp></myapp>); setTimeout(unmount, 1000); await waitUntilExit(); // resolves after `unmount()` is called
clear()

Clear output.

const {clear} = render(<myapp></myapp>); clear();

measureElement(ref)

Measure the dimensions of a particular

<box></box>

element. It 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 could use it when you need to change the layout based on the length of its content.

Note:

measureElement()

returns correct results only after the initial render, when layout has been calculated. Until then,

width

and

height

equal to zero. It's recommended to call

measureElement()

in a

useEffect

hook, which fires after the component has rendered.

ref

Type:

MutableRef

A reference to a

<box></box>

element captured with a

ref

property. See Refs for more information on how to capture references.

import {render, measureElement, Box, Text} from 'ink'; const Example = () =\> { const ref = useRef(); useEffect(() =\> { const {width, height} = measureElement(ref.current); // width = 100, height = 1 }, []); return ( <box width="{100}">
            <box ref="{ref}">
                <text>This box will stretch to 100 width</text>
            </box>
        </box> ); }; render(<example></example>);

Testing

Ink components are simple to test with ink-testing-library. Here's a simple example that checks how component is rendered:

import React from 'react'; import {Text} from 'ink'; import {render} from 'ink-testing-library'; const Test = () =\> Hello World; const {lastFrame} = render(<test></test>); lastFrame() === 'Hello World'; //=\> true

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, run it with

DEV=true

environment variable:

$ DEV=true my-cli

Then, start React Devtools itself:

$ npx react-devtools

After it starts up, you should see the component tree of your CLI. You can even inspect and change the props of components, and see the results immediatelly in the CLI, without restarting it.

Note: You must manually quit your CLI via Ctrl+C after you're done testing.

Useful Components

Useful Hooks

Examples

Maintainers

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.