npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@georgemichel/react-native-xprinter-manager

v1.0.0

Published

Complete XPrinter thermal printer management library with TCP/IP support, receipt printing, and auto-connect

Readme

React Native XPrinter Manager

A complete, standalone React Native library for managing XPrinter thermal printers over TCP/IP connection. Provides React hooks for connection management, printer storage, auto-connect functionality, and receipt printing.

Features

  • 📦 All Dependencies Included - No manual linking required
  • 🔌 Easy Connection Management - Connect/disconnect with simple hooks
  • 💾 Persistent Storage - Save printer configurations locally
  • 🔄 Auto-Connect - Automatically connect to saved printers on app start
  • 🧾 Receipt Printing - Pre-built receipt template with customization
  • 📝 ESC/POS Commands - Full suite of thermal printer commands
  • React Hooks - Modern React hooks API
  • 🎯 TypeScript Ready - (Types can be added)
  • 🚀 Production Ready - Battle-tested and documented

Installation

Install from Private NPM

One command - everything included!

npm install @yourcompany/react-native-xprinter-manager

That's it! All dependencies (react-native-tcp-socket, @react-native-async-storage/async-storage) are included automatically.

For Expo Projects

After installing, rebuild your native code:

npx expo prebuild
npm run android  # or npm run ios

Setup Authentication

Create .npmrc in your project root:

@yourcompany:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=YOUR-GITHUB-TOKEN

See SETUP.md for complete publishing and installation instructions.

Quick Start

1. Basic Connection

import React from 'react';
import { View, Button, Text } from 'react-native';
import { usePrinterConnection } from '@yourcompany/react-native-xprinter-manager';

function App() {
  const {
    isConnected,
    connectedPrinter,
    connect,
    disconnect,
    sendData
  } = usePrinterConnection();

  const handleConnect = async () => {
    try {
      await connect('192.168.100.99', 9100, 'Main Printer');
      alert('Connected!');
    } catch (error) {
      alert('Connection failed: ' + error.message);
    }
  };

  return (
    <View>
      {isConnected ? (
        <>
          <Text>Connected to: {connectedPrinter.deviceName}</Text>
          <Button title="Disconnect" onPress={disconnect} />
        </>
      ) : (
        <Button title="Connect" onPress={handleConnect} />
      )}
    </View>
  );
}

2. Print a Receipt

import { usePrinterConnection, printReceipt } from '@yourcompany/react-native-xprinter-manager';

function ReceiptScreen() {
  const { socket, isConnected } = usePrinterConnection();

  const handlePrint = async () => {
    if (!isConnected) {
      alert('Not connected to printer');
      return;
    }

    const receiptData = {
      storeName: "My Store",
      storeAddress: "123 Main St, City, State",
      storePhone: "(555) 123-4567",
      receiptNumber: "INV-001",
      items: [
        { name: "Coffee", qty: 2, price: 3.50 },
        { name: "Sandwich", qty: 1, price: 7.99 },
      ],
      subtotal: 14.99,
      tax: 1.20,
      total: 16.19,
      paymentMethod: "Cash",
      footerText: "Thank you!"
    };

    try {
      await printReceipt(socket, receiptData);
      alert('Receipt printed!');
    } catch (error) {
      alert('Print failed: ' + error.message);
    }
  };

  return (
    <Button title="Print Receipt" onPress={handlePrint} />
  );
}

3. Save and Auto-Connect

import {
  usePrinterConnection,
  usePrinterStorage,
  useAutoConnect
} from '@yourcompany/react-native-xprinter-manager';

function PrinterManager() {
  const { connect, isConnected } = usePrinterConnection();
  const { addPrinter, savedPrinters } = usePrinterStorage();
  const { isAutoConnecting } = useAutoConnect({ enabled: true });

  const handleAddPrinter = async () => {
    const printer = await addPrinter({
      ip: '192.168.100.99',
      port: 9100,
      deviceName: 'Main Counter Printer',
      autoConnect: true // Will auto-connect on app start
    });

    // Manually connect now
    await connect(printer.ip, printer.port, printer.deviceName);
  };

  return (
    <View>
      {isAutoConnecting && <Text>Auto-connecting...</Text>}
      {savedPrinters.map(printer => (
        <Text key={printer.id}>{printer.deviceName}</Text>
      ))}
      <Button title="Add Printer" onPress={handleAddPrinter} />
    </View>
  );
}

API Reference

Hooks

usePrinterConnection()

Manages TCP socket connection to printer.

Returns:

  • socket - Active socket object
  • isConnected - Connection status
  • isConnecting - Connecting in progress
  • connectedPrinter - Current printer info
  • error - Last error message
  • receivedData - Data received from printer
  • connect(ip, port, deviceName, options) - Connect to printer
  • disconnect() - Disconnect from printer
  • sendData(data, encoding) - Send data to printer
  • checkPrinterAvailable(ip, port, timeout) - Check if printer is online
  • clearReceivedData() - Clear received data buffer

usePrinterStorage()

Manages saved printer configurations.

Returns:

  • savedPrinters - Array of saved printers
  • isLoading - Loading status
  • addPrinter(printer) - Add new printer
  • removePrinter(printerId) - Remove printer
  • updatePrinter(printerId, updates) - Update printer
  • getPrinter(printerId) - Get printer by ID
  • getPrinterByAddress(ip, port) - Get printer by address
  • setAutoConnect(printerId, enabled) - Set auto-connect
  • getAutoConnectPrinters() - Get printers with auto-connect
  • updateLastConnected(printerId) - Update last connected time
  • clearAllPrinters() - Remove all printers
  • reload() - Reload from storage

useAutoConnect(options)

Automatically connects to saved printers on app start.

Options:

  • enabled - Enable auto-connect (default: true)
  • retryDelay - Delay between retries in ms (default: 3000)
  • maxRetries - Max retry attempts (default: 3)

Returns:

  • isAutoConnecting - Auto-connect in progress
  • autoConnectStatus - Array of connection attempts
  • triggerAutoConnect() - Manually trigger auto-connect
  • resetAutoConnect() - Reset auto-connect state

Utilities

printReceipt(socket, receiptData)

Prints a formatted receipt.

Parameters:

  • socket - Active TCP socket
  • receiptData - Receipt data object (see example above)

Returns: Promise<boolean>

Commands

ESC/POS command constants:

import { Commands } from '@yourcompany/react-native-xprinter-manager';

// Initialization
Commands.INIT

// Alignment
Commands.ALIGN_LEFT
Commands.ALIGN_CENTER
Commands.ALIGN_RIGHT

// Text Size
Commands.TEXT_SIZE_NORMAL
Commands.TEXT_SIZE_DOUBLE
Commands.TEXT_SIZE_LARGE

// Text Style
Commands.TEXT_BOLD_ON
Commands.TEXT_BOLD_OFF

// Paper Control
Commands.LINE_FEED
Commands.CUT_PAPER

Helper Functions

  • separator(char, length) - Create separator line
  • formatLine(left, right, totalWidth) - Format left/right aligned text
  • centerText(text, width) - Center text
  • formatCurrency(amount, currency) - Format currency

Receipt Template

The library includes a customizable receipt template. Here's how to modify it:

const receiptData = {
  // === HEADER ===
  storeName: "Your Store Name",           // Store name (centered, large)
  storeAddress: "123 Main St",            // Store address
  storePhone: "(555) 123-4567",           // Store phone

  // === RECEIPT INFO ===
  receiptNumber: "INV-001234",            // Invoice/order number

  // === ITEMS ===
  items: [
    {
      name: "Product Name",                // Item name
      qty: 2,                              // Quantity
      price: 10.00                         // Price per unit
    },
    // ... more items
  ],

  // === TOTALS ===
  subtotal: 45.00,                        // Subtotal
  tax: 3.60,                              // Tax amount
  total: 48.60,                           // Total amount

  // === PAYMENT ===
  paymentMethod: "Cash",                  // Payment method

  // === FOOTER ===
  footerText: "Thank you!\nVisit again!" // Footer message
};

Configuration for Private NPM

To publish as a private npm package:

  1. Update package.json:
{
  "name": "@yourcompany/react-native-xprinter-manager",
  "private": false,
  "publishConfig": {
    "registry": "https://npm.pkg.github.com/"
  }
}
  1. Publish:
cd lib
npm publish
  1. Install in projects:
npm install @yourcompany/react-native-xprinter-manager

Troubleshooting

Connection Issues

  1. Check IP and Port: Verify printer IP address and port (usually 9100)
  2. Network Connection: Ensure device is on same network as printer
  3. Firewall: Check if firewall is blocking TCP connections
  4. Printer Status: Ensure printer is powered on and online

Print Issues

  1. Paper Loaded: Verify paper is loaded correctly
  2. ESC/POS Support: Ensure printer supports ESC/POS commands
  3. Encoding: Try different text encodings if characters appear wrong
  4. Commands: Some printers may not support all ESC/POS commands

License

MIT

Support

For issues and questions, please open an issue on GitHub or contact support.