Day 1: React in Terminal 🎨
Valeria

Valeria @valeriavg

About: Re-inventor extraordinaire, optimisation addict and open web advocate.

Location:
Stockholm, Sweden
Joined:
Sep 23, 2020

Day 1: React in Terminal 🎨

Publish Date: Dec 1 '24
5 1

Ho-ho-ho! The time is finally here and, following the suggested format, the first gift I'd like to share with you is this amazing gem: https://term.ink/.

This library allows you to write terminal interfaces using React!

It works great with node, but the easiest way to try it out and avoid setting up TypeScript is by using Deno.

Install dependencies:

deno add npm:ink npm:react
Enter fullscreen mode Exit fullscreen mode

Create a script, e.g. main.tsx:

import React, { useState, useEffect } from "npm:react";
import { render, Text } from "npm:ink";

const Counter = () => {
  const [counter, setCounter] = useState<number>(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCounter((previousCounter: number) => previousCounter + 1);
    }, 100);

    return () => {
      clearInterval(timer);
    };
  }, []);

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

render(<Counter />);
Enter fullscreen mode Exit fullscreen mode

And run with deno run -A main.tsx:

Spinner showing X tests passed

But that's not all! How about something like this?

Counter with background

And the code for it is:

import React, { useState, useEffect } from "npm:react";
import { render, Text, Box } from "npm:ink";

const Counter = () => {
  const [counter, setCounter] = useState<number>(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setCounter((previousCounter: number) => previousCounter + 1);
    }, 100);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <Box borderStyle="double" margin={2} padding={2}>
      <Text backgroundColor="green">{counter}</Text> 
      <Text> tests passed</Text>
    </Box>
  );
};

render(<Counter />);
Enter fullscreen mode Exit fullscreen mode

Good luck with your next command line interface app!

Liked the content and would love to have more of it all year long?

Buy Me A Coffee

Comments 1 total

  • Peter Vivo
    Peter VivoDec 4, 2024

    Good to know this way still exists.

Add comment