or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-redbox-react

A React component for displaying JavaScript errors in a visual red screen of death format for development environments.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/redbox-react@1.6.x

To install, run

npx @tessl/cli install tessl/npm-redbox-react@1.6.0

index.mddocs/

Redbox React

Redbox React provides React components for displaying JavaScript errors in a visual red screen of death (RSOD) format during development. It renders error messages and stack traces in a formatted interface that makes debugging easier by displaying errors prominently where the application would normally render.

Package Information

  • Package Name: redbox-react
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install redbox-react

Core Imports

import RedBox from "redbox-react";

For named imports:

import RedBox, { RedBoxError } from "redbox-react";

For utility functions:

import { filenameWithoutLoaders, makeUrl, makeLinkText } from "redbox-react/lib";

CommonJS:

const RedBox = require("redbox-react").default;
const { RedBoxError } = require("redbox-react");

Basic Usage

import React from 'react';
import { render } from 'react-dom';
import RedBox from 'redbox-react';
import App from './components/App';

const root = document.getElementById('root');

if (__DEV__) {
  try {
    render(<App />, root);
  } catch (e) {
    render(<RedBox error={e} />, root);
  }
} else {
  render(<App />, root);
}

Capabilities

Portal Error Display

The main RedBox component renders errors in a portal (separate DOM element) to prevent CSS conflicts and ensure visibility.

import React from 'react';
import PropTypes from 'prop-types';

/**
 * Portal wrapper component that renders RedBoxError in a separate DOM element
 * @param error - The JavaScript Error object to display
 */
class RedBox extends React.Component {
  static propTypes = {
    error: PropTypes.instanceOf(Error).isRequired
  };
  static displayName = 'RedBox';
}

Usage Example:

import RedBox from 'redbox-react';

const error = new Error('Something went wrong!');

function App() {
  return <RedBox error={error} />;
}

Direct Error Rendering

The RedBoxError component provides direct error rendering with extensive customization options.

import React from 'react';
import PropTypes from 'prop-types';

/**
 * Core error display component with error parsing and rendering logic
 * @param error - The JavaScript Error object to display
 * @param filename - Override filename for the first stack frame
 * @param editorScheme - URL scheme for opening files in editor (e.g., 'subl', 'vscode')
 * @param useLines - Whether to display line numbers in stack trace (default: true)
 * @param useColumns - Whether to display column numbers in stack trace (default: true)
 * @param style - Custom style overrides (shallow merged with default styles)
 * @param className - CSS class name for the root redbox element
 */
class RedBoxError extends React.Component {
  static propTypes = {
    error: PropTypes.instanceOf(Error).isRequired,
    filename: PropTypes.string,
    editorScheme: PropTypes.string,
    useLines: PropTypes.bool,
    useColumns: PropTypes.bool,
    style: PropTypes.object,
    className: PropTypes.string
  };
  static displayName = 'RedBoxError';
  static defaultProps = {
    useLines: true,
    useColumns: true
  };
}

Usage Example:

import { RedBoxError } from 'redbox-react';

function ErrorDisplay({ error }) {
  return (
    <RedBoxError 
      error={error}
      editorScheme="vscode"
      useLines={true}
      useColumns={false}
      style={{
        redbox: { background: 'darkred' }
      }}
      className="custom-error-display"
    />
  );
}

Editor Integration

Open files directly in your editor from stack trace links by configuring the editor scheme.

Supported Editor Schemes:

  • Visual Studio Code: vscode - Creates vscode://file/path:line:column URLs
  • Sublime Text: subl - Creates subl://open?url=file://path&line=X&column=Y URLs
  • Custom schemes: Any scheme can be provided for custom editor integration

Usage Example:

import { RedBoxError } from 'redbox-react';

// Configure for Visual Studio Code
<RedBoxError error={error} editorScheme="vscode" />

// Configure for Sublime Text
<RedBoxError error={error} editorScheme="subl" />

Style Customization

Override default styles by providing a style object that gets shallow-merged with the defaults.

Available Style Properties:

  • redbox: Main container styles (fixed position overlay)
  • message: Error message text styles
  • stack: Stack trace container styles
  • frame: Individual stack frame styles
  • file: Filename text styles
  • linkToFile: File link styles

Usage Example:

const customStyles = {
  redbox: {
    background: 'rgb(139, 0, 0)', // Dark red instead of default red
    fontSize: '14px'
  },
  message: {
    fontWeight: 'normal',
    textDecoration: 'underline'
  }
};

<RedBoxError error={error} style={customStyles} />

Utility Functions

Helper functions for file path processing and URL generation used internally by redbox-react.

/**
 * Remove webpack loader syntax from filename
 * @param filename - Filename that may contain webpack loader syntax
 * @returns Filename without loader syntax
 */
function filenameWithoutLoaders(filename?: string): string;

/**
 * Check if filename contains webpack loader syntax
 * @param filename - Filename to check
 * @returns True if filename contains loader syntax
 */
function filenameHasLoaders(filename: string): boolean;

/**
 * Check if filename contains a URL scheme
 * @param filename - Filename to check
 * @returns True if filename has a scheme (e.g., http:, file:)
 */
function filenameHasSchema(filename: string): boolean;

/**
 * Check if filename is an absolute path
 * @param filename - Filename to check
 * @returns True if filename is absolute
 */
function isFilenameAbsolute(filename: string): boolean;

/**
 * Generate URL for opening file in editor
 * @param filename - File path
 * @param scheme - Editor URL scheme (e.g., 'vscode', 'subl')
 * @param line - Line number (optional)
 * @param column - Column number (optional)
 * @returns URL string for opening file in editor
 */
function makeUrl(filename: string, scheme?: string, line?: number, column?: number): string;

/**
 * Generate display text for file links
 * @param filename - File path
 * @param line - Line number (optional)
 * @param column - Column number (optional)
 * @returns Formatted text for display
 */
function makeLinkText(filename: string, line?: number, column?: number): string;

Usage Example:

import { filenameWithoutLoaders, makeUrl, makeLinkText } from 'redbox-react/lib';

// Clean webpack loader syntax from filename
const cleanFilename = filenameWithoutLoaders('babel-loader!./src/app.js');
// Result: './src/app.js'

// Generate editor URL
const editorUrl = makeUrl('/src/app.js', 'vscode', 42, 15);
// Result: 'vscode://file/src/app.js:42:15'

// Generate display text
const linkText = makeLinkText('/src/app.js', 42, 15);
// Result: '/src/app.js:42:15'

Types

import React from 'react';

/**
 * Props interface for both RedBox and RedBoxError components
 */
interface RedBoxProps extends React.Props<RedBoxError> {
  error: Error;                    // Required: JavaScript Error object to display
  filename?: string;               // Optional: Override filename for first stack frame
  editorScheme?: string;           // Optional: URL scheme for editor integration
  useLines?: boolean;              // Optional: Display line numbers (default: true)
  useColumns?: boolean;            // Optional: Display column numbers (default: true)
  style?: RedBoxStyles;            // Optional: Custom style overrides
  className?: string;              // Optional: CSS class name for root element
}

/**
 * Style object interface for customizing redbox appearance
 */
interface RedBoxStyles {
  redbox?: React.CSSProperties;    // Main container styles (fixed position overlay)
  message?: React.CSSProperties;   // Error message text styles
  stack?: React.CSSProperties;     // Stack trace container styles
  frame?: React.CSSProperties;     // Individual stack frame styles
  file?: React.CSSProperties;      // Filename text styles
  linkToFile?: React.CSSProperties; // File link styles
}

/**
 * Default style values used by redbox-react
 */
const defaultStyles: RedBoxStyles = {
  redbox: {
    boxSizing: 'border-box',
    fontFamily: 'sans-serif',
    position: 'fixed',
    padding: 10,
    top: '0px',
    left: '0px',
    bottom: '0px',
    right: '0px',
    width: '100%',
    background: 'rgb(204, 0, 0)',
    color: 'white',
    zIndex: 2147483647,
    textAlign: 'left',
    fontSize: '16px',
    lineHeight: 1.2,
    overflow: 'auto'
  },
  message: {
    fontWeight: 'bold'
  },
  stack: {
    fontFamily: 'monospace',
    marginTop: '2em'
  },
  frame: {
    marginTop: '1em'
  },
  file: {
    fontSize: '0.8em',
    color: 'rgba(255, 255, 255, 0.7)'
  },
  linkToFile: {
    textDecoration: 'none',
    color: 'rgba(255, 255, 255, 0.7)'
  }
};

Error Processing Features

Source Map Support

Redbox React automatically processes stack traces through source maps when available:

  • Webpack Eval: Automatically detects and handles webpack eval builds
  • Standard Eval: Processes standard JavaScript eval patterns
  • Source Maps: Uses sourcemapped-stacktrace for asynchronous source map processing
  • Error Stack Parser: Parses JavaScript error stacks with error-stack-parser

Stack Trace Enhancement

  • Clickable Links: Stack trace entries become clickable links when editor scheme is configured
  • Line/Column Numbers: Optionally display precise location information
  • File Path Processing: Handles webpack loaders and absolute/relative paths
  • Fallback Handling: Gracefully handles unparseable stack traces

Integration Patterns

React Transform Catch Errors

// .babelrc configuration
{
  "presets": ["react"],
  "env": {
    "development": {
      "plugins": [
        ["react-transform", {
          "transforms": [{
            "transform": "react-transform-catch-errors",
            "imports": ["react", "redbox-react"]
          }]
        }]
      ]
    }
  }
}

React Hot Loader

import { hot } from 'react-hot-loader/root';
import RedBox from 'redbox-react';

const App = () => {
  // Your app component
};

export default hot(App);

Webpack Integration

For accurate filenames in stack traces with Webpack:

// webpack.config.js
module.exports = {
  output: {
    devtoolModuleFilenameTemplate: '/[absolute-resource-path]'
  },
  devtool: 'eval'
};

Development Notes

  • Development Only: This component should only be used in development environments
  • Portal Rendering: RedBox renders outside the normal React tree to avoid CSS conflicts
  • Memory Management: Components properly clean up DOM elements on unmount
  • Error Boundaries: Compatible with React Error Boundaries for comprehensive error handling
  • Performance: Lazy evaluation of source map processing to avoid blocking rendering