Ink

React for interactive command-line apps

README

undefined




Ink



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

Build Status npm

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. If you're looking for docs on Ink 2, check out this release. There's also a migration guide from Ink 2 available.


My open source work is supported by the community ❤️

Special thanks to:
WorkOS
Your app, enterprise-ready.
Start selling to enterprise customers with just a few lines of code.
Add Single Sign-On (and more) in minutes instead of months.




Install


  1. ```sh
  2. npm install ink react
  3. ```

Usage


  1. ```jsx
  2. import React, {useState, useEffect} from 'react';
  3. import {render, Text} from 'ink';

  4. const Counter = () => {
  5. const [counter, setCounter] = useState(0);

  6. useEffect(() => {
  7.   const timer = setInterval(() => {
  8.    setCounter(previousCounter => previousCounter + 1);
  9.   }, 100);

  10.   return () => {
  11.    clearInterval(timer);
  12.   };
  13. }, []);

  14. return <Text color="green">{counter} tests passed</Text>;
  15. };

  16. render(<Counter />);
  17. ```


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?


- Cloudflare's Wrangler - The CLI for Cloudflare Workers.
- Gatsby - Gatsby is a modern web framework for blazing fast websites.
- tap - A Test-Anything-Protocol library for JavaScript.
- Terraform CDK - CDK (Cloud Development Kit) for HashiCorp Terraform.
- Twilio's SIGNAL - CLI for Twilio's SIGNAL conference. Blog post.
- Typewriter - Generates strongly-typed Segment analytics clients from arbitrary JSON Schema.
- Prisma - The unified data layer for modern applications.
- Wallace - Pretty CSS analytics.
- Blitz - The Fullstack React Framework.
- New York Times - NYT uses Inkkyt - a toolkit that encapsulates and manages the configuration for web apps.
- tink - Next-generation runtime and package manager.
- Inkle - Wordle game.
- loki - Visual regression testing for Storybook.
- Bit - Build, distribute and collaborate on components.
- Remirror - Your friendly, world-class editor toolkit.
- Prime - Open source GraphQL CMS.
- Splash - Observe the splash zone of a change across the Shopify's Polaris component library.
- emoj - Find relevant emojis.
- emma - Find and install npm packages.
- swiff - Multi-environment command line tools for time-saving web developers.
- share - Quickly share files.
- Kubelive - CLI for Kubernetes to provide live data about the cluster and its resources.
- changelog-view - View changelogs.
- cfpush - An interactive Cloud Foundry tutorial.
- startd - Turn your React component into a web app.
- wiki-cli - Search Wikipedia and read summaries.
- garson - Build interactive config-based command-line interfaces.
- git-contrib-calendar - Display a contributions calendar for any git repository.
- gitgud - An interactive command-line GUI for Git.
- Autarky - Find and delete oldnode_modules directories in order to free up disk space.
- fast-cli - Test your download and upload speed.
- tasuku - Minimal task runner.
- mnswpr - Minesweeper game.
- lrn - Learning by repetition.
- turdle - Wordle game.
- Shopify CLI - Build apps, themes, and storefronts for Shopify.

Contents


- [``](#text) - [``](#box) - [``](#newline) - [``](#spacer) - [``](#static) - [``](#transform)
- [useInput](#useinputinputhandler-options)
- [useApp](#useapp)
- [useStdin](#usestdin)
- [useStdout](#usestdout)
- [useStderr](#usestderr)
- [useFocus](#usefocusoptions)
- [useFocusManager](#usefocusmanager)
- API

Getting Started


Use create-ink-app to quickly scaffold a new Ink-based CLI.

  1. ```sh
  2. mkdir my-ink-cli
  3. cd my-ink-cli
  4. npx create-ink-app
  5. ```

Alternatively, create a TypeScript project:

  1. ```sh
  2. npx create-ink-app --typescript
  3. ```

Manual 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:

  1. ```sh
  2. npm install --save-dev @babel/preset-react
  3. ```

  1. ```json
  2. {
  3. "presets": [
  4.   "@babel/preset-react",
  5.   [
  6.    "@babel/preset-env",
  7.    {
  8.     "targets": {
  9.      "node": true
  10.     }
  11.    }
  12.   ]
  13. ]
  14. }
  15. ```

Next, create a file source.js, where you'll type code that uses Ink:

  1. ```jsx
  2. import React from 'react';
  3. import {render, Text} from 'ink';

  4. const Demo = () => <Text>Hello World</Text>;

  5. render(<Demo />);
  6. ```

Then, transpile this file with Babel:

  1. ```sh
  2. npx babel source.js -o cli.js
  3. ```

Now you can run cli.js with Node.js:

  1. ```sh
  2. node cli
  3. ```

If you don't like transpiling files during development, you can use import-jsx torequire() 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 [``](#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.

Components


### ``

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

  1. ```jsx
  2. import {render, Text} from 'ink';

  3. const Example = () => (
  4. <>
  5.   <Text color="green">I am green</Text>
  6.   <Text color="black" backgroundColor="white">
  7.    I am black on white
  8.   </Text>
  9.   <Text color="#ffffff">I am white</Text>
  10.   <Text bold>I am bold</Text>
  11.   <Text italic>I am italic</Text>
  12.   <Text underline>I am underline</Text>
  13.   <Text strikethrough>I am strikethrough</Text>
  14.   <Text inverse>I am inversed</Text>
  15. </>
  16. );

  17. render(<Example />);
  18. ```

**Note:** `` allows only text nodes and nested `` components inside of it. For example, `` component can't be used inside ``.

color


Type: string

Change text color.
Ink uses chalk under the hood, so all its functionality is supported.

  1. ```jsx
  2. <Text color="green">Green</Text>
  3. <Text color="#005cc5">Blue</Text>
  4. <Text color="rgb(232, 131, 136)">Red</Text>
  5. ```


backgroundColor


Type: string

Same as color above, but for background.

  1. ```jsx
  2. <Text backgroundColor="green" color="white">Green</Text>
  3. <Text backgroundColor="#005cc5" color="white">Blue</Text>
  4. <Text backgroundColor="rgb(232, 131, 136)" color="white">Red</Text>
  5. ```


dimColor


Type: boolean\
Default: false

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

  1. ```jsx
  2. <Text color="red" dimColor>
  3. Dimmed Red
  4. </Text>
  5. ```


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.

inverse


Type: boolean\
Default: false

Inverse background and foreground colors.

  1. ```jsx
  2. <Text inverse color="yellow">
  3. Inversed Yellow
  4. </Text>
  5. ```


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.

  1. ```jsx
  2. <Box width={7}>
  3. <Text>Hello World</Text>
  4. </Box>
  5. //=> 'Hello\nWorld'

  6. // `truncate` is an alias to `truncate-end`
  7. <Box width={7}>
  8. <Text wrap="truncate">Hello World</Text>
  9. </Box>
  10. //=> 'Hello…'

  11. <Box width={7}>
  12. <Text wrap="truncate-middle">Hello World</Text>
  13. </Box>
  14. //=> 'He…ld'

  15. <Box width={7}>
  16. <Text wrap="truncate-start">Hello World</Text>
  17. </Box>
  18. //=> '…World'
  19. ```

### ``

`` is an essential Ink component to build your layout.It's like `
` in the browser.

  1. ```jsx
  2. import {render, Box, Text} from 'ink';

  3. const Example = () => (
  4. <Box margin={2}>
  5.   <Text>This is a box with margin</Text>
  6. </Box>
  7. );

  8. render(<Example />);
  9. ```

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.

  1. ```jsx
  2. <Box width={4}>
  3. <Text>X</Text>
  4. </Box>
  5. //=> 'X   '
  6. ```

  1. ```jsx
  2. <Box width={10}>
  3. <Box width="50%">
  4.   <Text>X</Text>
  5. </Box>
  6. <Text>Y</Text>
  7. </Box>
  8. //=> 'X    Y'
  9. ```

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.

  1. ```jsx
  2. <Box height={4}>
  3. <Text>X</Text>
  4. </Box>
  5. //=> 'X\n\n\n'
  6. ```

  1. ```jsx
  2. <Box height={6} flexDirection="column">
  3. <Box height="50%">
  4.   <Text>X</Text>
  5. </Box>
  6. <Text>Y</Text>
  7. </Box>
  8. //=> 'X\n\n\nY\n\n'
  9. ```

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.

  1. ```jsx
  2. <Box paddingTop={2}>Top</Box>
  3. <Box paddingBottom={2}>Bottom</Box>
  4. <Box paddingLeft={2}>Left</Box>
  5. <Box paddingRight={2}>Right</Box>
  6. <Box paddingX={2}>Left and right</Box>
  7. <Box paddingY={2}>Top and bottom</Box>
  8. <Box padding={2}>Top, bottom, left and right</Box>
  9. ```

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.

  1. ```jsx
  2. <Box marginTop={2}>Top</Box>
  3. <Box marginBottom={2}>Bottom</Box>
  4. <Box marginLeft={2}>Left</Box>
  5. <Box marginRight={2}>Right</Box>
  6. <Box marginX={2}>Left and right</Box>
  7. <Box marginY={2}>Top and bottom</Box>
  8. <Box margin={2}>Top, bottom, left and right</Box>
  9. ```

Flex


flexGrow

Type: number\
Default: 0


  1. ```jsx
  2. <Box>
  3. <Text>Label:</Text>
  4. <Box flexGrow={1}>
  5.   <Text>Fills all remaining space</Text>
  6. </Box>
  7. </Box>
  8. ```

flexShrink

Type: number\
Default: 1


  1. ```jsx
  2. <Box width={20}>
  3. <Box flexShrink={2} width={10}>
  4.   <Text>Will be 1/4Text>
  5. </Box>
  6. <Box width={10}>
  7.   <Text>Will be 3/4Text>
  8. </Box>
  9. </Box>
  10. ```

flexBasis

Type: number string


  1. ```jsx
  2. <Box width={6}>
  3. <Box flexBasis={3}>
  4.   <Text>X</Text>
  5. </Box>
  6. <Text>Y</Text>
  7. </Box>
  8. //=> 'X  Y'
  9. ```

  1. ```jsx
  2. <Box width={6}>
  3. <Box flexBasis="50%">
  4.   <Text>X</Text>
  5. </Box>
  6. <Text>Y</Text>
  7. </Box>
  8. //=> 'X  Y'
  9. ```

flexDirection

Type: string\
Allowed values: row row-reverse column column-reverse


  1. ```jsx
  2. <Box>
  3. <Box marginRight={1}>
  4.   <Text>X</Text>
  5. </Box>
  6. <Text>Y</Text>
  7. </Box>
  8. // X Y

  9. <Box flexDirection="row-reverse">
  10. <Text>X</Text>
  11. <Box marginRight={1}>
  12.   <Text>Y</Text>
  13. </Box>
  14. </Box>
  15. // Y X

  16. <Box flexDirection="column">
  17. <Text>X</Text>
  18. <Text>Y</Text>
  19. </Box>
  20. // X
  21. // Y

  22. <Box flexDirection="column-reverse">
  23. <Text>X</Text>
  24. <Text>Y</Text>
  25. </Box>
  26. // Y
  27. // X
  28. ```

alignItems

Type: string\
Allowed values: flex-start center flex-end


  1. ```jsx
  2. <Box alignItems="flex-start">
  3. <Box marginRight={1}>
  4.   <Text>X</Text>
  5. </Box>
  6. <Text>
  7.   A
  8.   <Newline/>
  9.   B
  10.   <Newline/>
  11.   C
  12. </Text>
  13. </Box>
  14. // X A
  15. //   B
  16. //   C

  17. <Box alignItems="center">
  18. <Box marginRight={1}>
  19.   <Text>X</Text>
  20. </Box>
  21. <Text>
  22.   A
  23.   <Newline/>
  24.   B
  25.   <Newline/>
  26.   C
  27. </Text>
  28. </Box>
  29. //   A
  30. // X B
  31. //   C

  32. <Box alignItems="flex-end">
  33. <Box marginRight={1}>
  34.   <Text>X</Text>
  35. </Box>
  36. <Text>
  37.   A
  38.   <Newline/>
  39.   B
  40.   <Newline/>
  41.   C
  42. </Text>
  43. </Box>
  44. //   A
  45. //   B
  46. // X C
  47. ```

alignSelf

Type: string\
Default: auto\
Allowed values: auto flex-start center flex-end


  1. ```jsx
  2. <Box height={3}>
  3. <Box alignSelf="flex-start">
  4.   <Text>X</Text>
  5. </Box>
  6. </Box>
  7. // X
  8. //
  9. //

  10. <Box height={3}>
  11. <Box alignSelf="center">
  12.   <Text>X</Text>
  13. </Box>
  14. </Box>
  15. //
  16. // X
  17. //

  18. <Box height={3}>
  19. <Box alignSelf="flex-end">
  20.   <Text>X</Text>
  21. </Box>
  22. </Box>
  23. //
  24. //
  25. // X
  26. ```

justifyContent

Type: string\
Allowed values: flex-start center flex-end space-between space-around


  1. ```jsx
  2. <Box justifyContent="flex-start">
  3. <Text>X</Text>
  4. </Box>
  5. // [X      ]

  6. <Box justifyContent="center">
  7. <Text>X</Text>
  8. </Box>
  9. // [   X   ]

  10. <Box justifyContent="flex-end">
  11. <Text>X</Text>
  12. </Box>
  13. // [      X]

  14. <Box justifyContent="space-between">
  15. <Text>X</Text>
  16. <Text>Y</Text>
  17. </Box>
  18. // [X      Y]

  19. <Box justifyContent="space-around">
  20. <Text>X</Text>
  21. <Text>Y</Text>
  22. </Box>
  23. // [  X   Y  ]
  24. ```

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.

  1. ```jsx
  2. <Box flexDirection="column">
  3. <Box>
  4.   <Box borderStyle="single" marginRight={2}>
  5.    <Text>single</Text>
  6.   </Box>
  7. <Box borderStyle="double" marginRight={2}>
  8.    <Text>double</Text>
  9.   </Box>
  10. <Box borderStyle="round" marginRight={2}>
  11.    <Text>round</Text>
  12.   </Box>
  13. <Box borderStyle="bold">
  14.    <Text>bold</Text>
  15.   </Box>
  16. </Box>
  17. <Box marginTop={1}>
  18.   <Box borderStyle="singleDouble" marginRight={2}>
  19.    <Text>singleDouble</Text>
  20.   </Box>
  21. <Box borderStyle="doubleSingle" marginRight={2}>
  22.    <Text>doubleSingle</Text>
  23.   </Box>
  24. <Box borderStyle="classic">
  25.    <Text>classic</Text>
  26.   </Box>
  27. </Box>
  28. </Box>
  29. ```


See example in examples/borders.

borderColor

Type: string

Change border color.
Accepts the same values as [`color`](#color) in `` component.

  1. ```jsx
  2. <Box borderStyle="round" borderColor="green">
  3. <Text>Green Rounded Box</Text>
  4. </Box>
  5. ```


### ``

Adds one or more newline (\n) characters.
Must be used within `` components.

count


Type: number\
Default: 1

Number of newlines to insert.

  1. ```jsx
  2. import {render, Text, Newline} from 'ink';

  3. const Example = () => (
  4. <Text>
  5.   <Text color="green">Hello</Text>
  6.   <Newline />
  7.   <Text color="red">World</Text>
  8. </Text>
  9. );

  10. render(<Example />);
  11. ```

Output:

  1. ```
  2. Hello
  3. World
  4. ```

### ``

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 `` in a `` with default flex direction (`row`) will position "Left" on the left side and will push "Right" to the right side.

  1. ```jsx
  2. import {render, Box, Text, Spacer} from 'ink';

  3. const Example = () => (
  4. <Box>
  5.   <Text>Left</Text>
  6.   <Spacer />
  7.   <Text>Right</Text>
  8. </Box>
  9. );

  10. render(<Example />);
  11. ```

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.

  1. ```jsx
  2. import {render, Box, Text, Spacer} from 'ink';

  3. const Example = () => (
  4. <Box flexDirection="column" height={10}>
  5.   <Text>Top</Text>
  6.   <Spacer />
  7.   <Text>Bottom</Text>
  8. </Box>
  9. );

  10. render(<Example />);
  11. ```

### ``

`` 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 `` for use cases like these, when you can't know
or control the amount of items that need to be rendered.

For example, [Tap](https://github.com/tapjs/node-tap) uses `` to display
a list of completed tests. Gatsby uses it
to display a list of generated pages, while still displaying a live progress bar.

  1. ```jsx
  2. import React, {useState, useEffect} from 'react';
  3. import {render, Static, Box, Text} from 'ink';

  4. const Example = () => {
  5. const [tests, setTests] = useState([]);

  6. useEffect(() => {
  7.   let completedTests = 0;
  8.   let timer;

  9.   const run = () => {
  10.    // Fake 10 completed tests
  11.    if (completedTests++ < 10) {
  12.     setTests(previousTests => [
  13.      ...previousTests,
  14.      {
  15.       id: previousTests.length,
  16.       title: `Test #${previousTests.length + 1}`
  17.      }
  18.     ]);

  19.     setTimeout(run, 100);
  20.    }
  21.   };

  22.   run();

  23.   return () => {
  24.    clearTimeout(timer);
  25.   };
  26. }, []);

  27. return (
  28.   <>
  29.    {/* This part will be rendered once to the terminal */}
  30.    <Static items={tests}>
  31.     {test => (
  32.      <Box key={test.id}>
  33.       <Text color="green"> {test.title}</Text>
  34.      </Box>
  35.     )}
  36.    </Static>

  37.    {/* This part keeps updating as state changes */}
  38.    <Box marginTop={1}>
  39.     <Text dimColor>Completed tests: {tests.length}</Text>
  40.    </Box>
  41.   </>
  42. );
  43. };

  44. render(<Example />);
  45. ```

**Note:** `` 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](examples/static/static.js) for an example usage of `` 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) for supported properties.

  1. ```jsx
  2. <Static items={...} style={{padding: 1}}>
  3. {...}
  4. </Static>
  5. ```

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.

  1. ```jsx
  2. <Static items={['a', 'b', 'c']}>
  3. {(item, index) => {
  4.   // This function is called for every item in ['a', 'b', 'c']
  5.   // `item` is 'a', 'b', 'c'
  6.   // `index` is 0, 1, 2
  7.   return (
  8.    <Box key={index}>
  9.     <Text>Item: {item}</Text>
  10.    </Box>
  11.   );
  12. }}
  13. </Static>
  14. ```

### ``

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 `` component does, it gives you an output string of its child components and lets you transform it in any way.

**Note:** `` must be applied only to `` children components and shouldn't change the dimensions of the output, otherwise layout will be incorrect.

  1. ```jsx
  2. import {render, Transform} from 'ink';

  3. const Example = () => (
  4. <Transform transform={output => output.toUpperCase()}>
  5.   <Text>Hello World</Text>
  6. </Transform>
  7. );

  8. render(<Example />);
  9. ```

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 convenient 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.

  1. ```jsx
  2. import {useInput} from 'ink';

  3. const UserInput = () => {
  4. useInput((input, key) => {
  5.   if (input === 'q') {
  6.    // Exit program
  7.   }

  8.   if (key.leftArrow) {
  9.    // Left arrow key pressed
  10.   }
  11. });

  12. return
  13. };
  14. ```

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.pageDown

key.pageUp

Type: boolean\
Default: false

If Page Up or Page Down key was pressed, the corresponding property will be true.
For example, if user presses Page Down, key.pageDown equals true.

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](waituntilexit) will reject with that error.

  1. ```js
  2. import {useApp} from 'ink';

  3. const Example = () => {
  4. const {exit} = useApp();

  5. // Exit the app after 5 seconds
  6. useEffect(() => {
  7.   setTimeout(() => {
  8.    exit();
  9.   }, 5000);
  10. }, []);

  11. return
  12. };
  13. ```

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.

  1. ```js
  2. import {useStdin} from 'ink';

  3. const Example = () => {
  4. const {stdin} = useStdin();

  5. return
  6. };
  7. ```

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.

  1. ```jsx
  2. import {useStdin} from 'ink';

  3. const Example = () => {
  4. const {isRawModeSupported} = useStdin();

  5. return isRawModeSupported ? (
  6.   <MyInputComponent />
  7. ) : (
  8.   <MyComponentThatDoesntUseInput />
  9. );
  10. };
  11. ```

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](#israwmodesupported) to detect setRawMode support.

  1. ```js
  2. import {useStdin} from 'ink';

  3. const Example = () => {
  4. const {setRawMode} = useStdin();

  5. useEffect(() => {
  6.   setRawMode(true);

  7.   return () => {
  8.    setRawMode(false);
  9.   };
  10. });

  11. return
  12. };
  13. ```

useStdout()


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

stdout


Type: stream.Writable\
Default: process.stdout

  1. ```js
  2. import {useStdout} from 'ink';

  3. const Example = () => {
  4. const {stdout} = useStdout;

  5. return
  6. };
  7. ```

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 ``, except it can't accept components, it only works with strings.

data

Type: string

Data to write to stdout.

  1. ```js
  2. import {useStdout} from 'ink';

  3. const Example = () => {
  4. const {write} = useStdout();

  5. useEffect(() => {
  6.   // Write a single message to stdout, above Ink's output
  7.   write('Hello from Ink to stdout\n');
  8. }, []);

  9. return
  10. };
  11. ```

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.

  1. ```js
  2. import {useStderr} from 'ink';

  3. const Example = () => {
  4. const {stderr} = useStderr();

  5. return
  6. };
  7. ```

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 ``, except it can't accept components, it only works with strings.

data

Type: string

Data to write to stderr.

  1. ```js
  2. import {useStderr} from 'ink';

  3. const Example = () => {
  4. const {write} = useStderr();

  5. useEffect(() => {
  6.   // Write a single message to stderr, above Ink's output
  7.   write('Hello from Ink to stderr\n');
  8. }, []);

  9. return
  10. };
  11. ```

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.

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.

  1. ```jsx
  2. import {render, useFocus, Text} from 'ink';

  3. const Example = () => {
  4. const {isFocused} = useFocus();

  5. return <Text>{isFocused ? 'I am focused' : 'I am not focused'}</Text>;
  6. };

  7. render(<Example />);
  8. ```


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.

  1. ```js
  2. import {useFocusManager} from 'ink';

  3. const Example = () => {
  4. const {enableFocus} = useFocusManager();

  5. useEffect(() => {
  6.   enableFocus();
  7. }, []);

  8. return
  9. };
  10. ```

disableFocus()


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

  1. ```js
  2. import {useFocusManager} from 'ink';

  3. const Example = () => {
  4. const {disableFocus} = useFocusManager();

  5. useEffect(() => {
  6.   disableFocus();
  7. }, []);

  8. return
  9. };
  10. ```

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.

  1. ```js
  2. import {useFocusManager} from 'ink';

  3. const Example = () => {
  4. const {focusNext} = useFocusManager();

  5. useEffect(() => {
  6.   focusNext();
  7. }, []);

  8. return
  9. };
  10. ```

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.

  1. ```js
  2. import {useFocusManager} from 'ink';

  3. const Example = () => {
  4. const {focusPrevious} = useFocusManager();

  5. useEffect(() => {
  6.   focusPrevious();
  7. }, []);

  8. return
  9. };
  10. ```

focus(id)


id

Type: string

Switch focus to the component with the given [id](#id).
If there's no component with that ID, focus will be given to the next focusable component.

  1. ```js
  2. import {useFocusManager, useInput} from 'ink';

  3. const Example = () => {
  4. const {focus} = useFocusManager();

  5. useInput(input => {
  6.   if (input === 's') {
  7.    // Focus the component with focus ID 'someId'
  8.    focus('someId');
  9.   }
  10. });

  11. return
  12. };
  13. ```

API


render(tree, options?)


Returns: [Instance](#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

  1. ```jsx
  2. // Update props of the root node
  3. const {rerender} = render(<Counter count={1} />);
  4. rerender(<Counter count={2} />);

  5. // Replace root node
  6. const {rerender} = render(<OldCounter />);
  7. rerender(<NewCounter />);
  8. ```

unmount()

Manually unmount the whole Ink app.

  1. ```jsx
  2. const {unmount} = render(<MyApp />);
  3. unmount();
  4. ```

waitUntilExit()

Returns a promise, which resolves when app is unmounted.

  1. ```jsx
  2. const {unmount, waitUntilExit} = render(<MyApp />);

  3. setTimeout(unmount, 1000);

  4. await waitUntilExit(); // resolves after `unmount()` is called
  5. ```

clear()

Clear output.

  1. ```jsx
  2. const {clear} = render(<MyApp />);
  3. clear();
  4. ```

measureElement(ref)


Measure the dimensions of a particular `` 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 `` element captured with a `ref` property.
See Refs for more information on how to capture references.

  1. ```jsx
  2. import {render, measureElement, Box, Text} from 'ink';

  3. const Example = () => {
  4. const ref = useRef();

  5. useEffect(() => {
  6.   const {width, height} = measureElement(ref.current);
  7.   // width = 100, height = 1
  8. }, []);

  9. return (
  10.   <Box width={100}>
  11.    <Box ref={ref}>
  12.     <Text>This box will stretch to 100 width</Text>
  13.    </Box>
  14.   </Box>
  15. );
  16. };

  17. render(<Example />);
  18. ```

Testing


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

  1. ```jsx
  2. import React from 'react';
  3. import {Text} from 'ink';
  4. import {render} from 'ink-testing-library';

  5. const Test = () => <Text>Hello World</Text>;
  6. const {lastFrame} = render(<Test />);

  7. lastFrame() === 'Hello World'; //=> true
  8. ```

Check out ink-testing-library for more examples and full documentation.

Using React Devtools


undefined

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:

  1. ```sh
  2. DEV=true my-cli
  3. ```

Then, start React Devtools itself:

  1. ```sh
  2. npx react-devtools
  3. ```

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


- ink-text-input - Text input.
- ink-spinner - Spinner.
- ink-select-input - Select (dropdown) input.
- ink-link - Link.
- ink-gradient - Gradient color.
- ink-big-text - Awesome text.
- ink-image - Display images inside the terminal.
- ink-tab - Tab.
- ink-color-pipe - Create color text with simpler style strings.
- ink-multi-select - Select one or more values from a list
- ink-divider - A divider.
- ink-progress-bar - Progress bar.
- ink-table - Table.
- ink-ascii - Awesome text component with more font choices, based on Figlet.
- ink-markdown - Render syntax highlighted Markdown.
- ink-quicksearch-input - Select component with fast quicksearch-like navigation.
- ink-confirm-input - Yes/No confirmation input.
- ink-syntax-highlight - Code syntax highlighting.
- ink-form - Form.
- ink-task-list - Task list.

Useful Hooks


- ink-use-stdout-dimensions - Subscribe to stdout dimensions.

Examples


- Jest - Implementation of basic Jest UI (live demo).
- Counter - Simple counter that increments every 100ms (live demo).
- Form with Validation - Manage form state using Final Form.
- [Borders](examples/borders/borders.js) - Add borders to `` component.
- Suspense - Use React Suspense.
- Table - Render a table with multiple columns and rows.
- Focus Management - UseuseFocus hook to manage focus between components.
- User Input - Listen to user input.
- Write to stdout - Write to stdout bypassing main Ink output.
- Write to stderr - Write to stderr bypassing main Ink output.
- [Static](examples/static/static.js) - Use `` to render permanent output.
- Child process - Render output from a child process.

Maintainers