0
# Redbox React
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: redbox-react
7
- **Package Type**: npm
8
- **Language**: JavaScript with TypeScript definitions
9
- **Installation**: `npm install redbox-react`
10
11
## Core Imports
12
13
```javascript
14
import RedBox from "redbox-react";
15
```
16
17
For named imports:
18
19
```javascript
20
import RedBox, { RedBoxError } from "redbox-react";
21
```
22
23
For utility functions:
24
25
```javascript
26
import { filenameWithoutLoaders, makeUrl, makeLinkText } from "redbox-react/lib";
27
```
28
29
CommonJS:
30
31
```javascript
32
const RedBox = require("redbox-react").default;
33
const { RedBoxError } = require("redbox-react");
34
```
35
36
## Basic Usage
37
38
```javascript
39
import React from 'react';
40
import { render } from 'react-dom';
41
import RedBox from 'redbox-react';
42
import App from './components/App';
43
44
const root = document.getElementById('root');
45
46
if (__DEV__) {
47
try {
48
render(<App />, root);
49
} catch (e) {
50
render(<RedBox error={e} />, root);
51
}
52
} else {
53
render(<App />, root);
54
}
55
```
56
57
## Capabilities
58
59
### Portal Error Display
60
61
The main RedBox component renders errors in a portal (separate DOM element) to prevent CSS conflicts and ensure visibility.
62
63
```javascript { .api }
64
import React from 'react';
65
import PropTypes from 'prop-types';
66
67
/**
68
* Portal wrapper component that renders RedBoxError in a separate DOM element
69
* @param error - The JavaScript Error object to display
70
*/
71
class RedBox extends React.Component {
72
static propTypes = {
73
error: PropTypes.instanceOf(Error).isRequired
74
};
75
static displayName = 'RedBox';
76
}
77
```
78
79
**Usage Example:**
80
81
```javascript
82
import RedBox from 'redbox-react';
83
84
const error = new Error('Something went wrong!');
85
86
function App() {
87
return <RedBox error={error} />;
88
}
89
```
90
91
### Direct Error Rendering
92
93
The RedBoxError component provides direct error rendering with extensive customization options.
94
95
```javascript { .api }
96
import React from 'react';
97
import PropTypes from 'prop-types';
98
99
/**
100
* Core error display component with error parsing and rendering logic
101
* @param error - The JavaScript Error object to display
102
* @param filename - Override filename for the first stack frame
103
* @param editorScheme - URL scheme for opening files in editor (e.g., 'subl', 'vscode')
104
* @param useLines - Whether to display line numbers in stack trace (default: true)
105
* @param useColumns - Whether to display column numbers in stack trace (default: true)
106
* @param style - Custom style overrides (shallow merged with default styles)
107
* @param className - CSS class name for the root redbox element
108
*/
109
class RedBoxError extends React.Component {
110
static propTypes = {
111
error: PropTypes.instanceOf(Error).isRequired,
112
filename: PropTypes.string,
113
editorScheme: PropTypes.string,
114
useLines: PropTypes.bool,
115
useColumns: PropTypes.bool,
116
style: PropTypes.object,
117
className: PropTypes.string
118
};
119
static displayName = 'RedBoxError';
120
static defaultProps = {
121
useLines: true,
122
useColumns: true
123
};
124
}
125
```
126
127
**Usage Example:**
128
129
```javascript
130
import { RedBoxError } from 'redbox-react';
131
132
function ErrorDisplay({ error }) {
133
return (
134
<RedBoxError
135
error={error}
136
editorScheme="vscode"
137
useLines={true}
138
useColumns={false}
139
style={{
140
redbox: { background: 'darkred' }
141
}}
142
className="custom-error-display"
143
/>
144
);
145
}
146
```
147
148
### Editor Integration
149
150
Open files directly in your editor from stack trace links by configuring the editor scheme.
151
152
**Supported Editor Schemes:**
153
154
- **Visual Studio Code**: `vscode` - Creates `vscode://file/path:line:column` URLs
155
- **Sublime Text**: `subl` - Creates `subl://open?url=file://path&line=X&column=Y` URLs
156
- **Custom schemes**: Any scheme can be provided for custom editor integration
157
158
**Usage Example:**
159
160
```javascript
161
import { RedBoxError } from 'redbox-react';
162
163
// Configure for Visual Studio Code
164
<RedBoxError error={error} editorScheme="vscode" />
165
166
// Configure for Sublime Text
167
<RedBoxError error={error} editorScheme="subl" />
168
```
169
170
### Style Customization
171
172
Override default styles by providing a style object that gets shallow-merged with the defaults.
173
174
**Available Style Properties:**
175
- `redbox`: Main container styles (fixed position overlay)
176
- `message`: Error message text styles
177
- `stack`: Stack trace container styles
178
- `frame`: Individual stack frame styles
179
- `file`: Filename text styles
180
- `linkToFile`: File link styles
181
182
**Usage Example:**
183
184
```javascript
185
const customStyles = {
186
redbox: {
187
background: 'rgb(139, 0, 0)', // Dark red instead of default red
188
fontSize: '14px'
189
},
190
message: {
191
fontWeight: 'normal',
192
textDecoration: 'underline'
193
}
194
};
195
196
<RedBoxError error={error} style={customStyles} />
197
```
198
199
### Utility Functions
200
201
Helper functions for file path processing and URL generation used internally by redbox-react.
202
203
```javascript { .api }
204
/**
205
* Remove webpack loader syntax from filename
206
* @param filename - Filename that may contain webpack loader syntax
207
* @returns Filename without loader syntax
208
*/
209
function filenameWithoutLoaders(filename?: string): string;
210
211
/**
212
* Check if filename contains webpack loader syntax
213
* @param filename - Filename to check
214
* @returns True if filename contains loader syntax
215
*/
216
function filenameHasLoaders(filename: string): boolean;
217
218
/**
219
* Check if filename contains a URL scheme
220
* @param filename - Filename to check
221
* @returns True if filename has a scheme (e.g., http:, file:)
222
*/
223
function filenameHasSchema(filename: string): boolean;
224
225
/**
226
* Check if filename is an absolute path
227
* @param filename - Filename to check
228
* @returns True if filename is absolute
229
*/
230
function isFilenameAbsolute(filename: string): boolean;
231
232
/**
233
* Generate URL for opening file in editor
234
* @param filename - File path
235
* @param scheme - Editor URL scheme (e.g., 'vscode', 'subl')
236
* @param line - Line number (optional)
237
* @param column - Column number (optional)
238
* @returns URL string for opening file in editor
239
*/
240
function makeUrl(filename: string, scheme?: string, line?: number, column?: number): string;
241
242
/**
243
* Generate display text for file links
244
* @param filename - File path
245
* @param line - Line number (optional)
246
* @param column - Column number (optional)
247
* @returns Formatted text for display
248
*/
249
function makeLinkText(filename: string, line?: number, column?: number): string;
250
```
251
252
**Usage Example:**
253
254
```javascript
255
import { filenameWithoutLoaders, makeUrl, makeLinkText } from 'redbox-react/lib';
256
257
// Clean webpack loader syntax from filename
258
const cleanFilename = filenameWithoutLoaders('babel-loader!./src/app.js');
259
// Result: './src/app.js'
260
261
// Generate editor URL
262
const editorUrl = makeUrl('/src/app.js', 'vscode', 42, 15);
263
// Result: 'vscode://file/src/app.js:42:15'
264
265
// Generate display text
266
const linkText = makeLinkText('/src/app.js', 42, 15);
267
// Result: '/src/app.js:42:15'
268
```
269
270
## Types
271
272
```javascript { .api }
273
import React from 'react';
274
275
/**
276
* Props interface for both RedBox and RedBoxError components
277
*/
278
interface RedBoxProps extends React.Props<RedBoxError> {
279
error: Error; // Required: JavaScript Error object to display
280
filename?: string; // Optional: Override filename for first stack frame
281
editorScheme?: string; // Optional: URL scheme for editor integration
282
useLines?: boolean; // Optional: Display line numbers (default: true)
283
useColumns?: boolean; // Optional: Display column numbers (default: true)
284
style?: RedBoxStyles; // Optional: Custom style overrides
285
className?: string; // Optional: CSS class name for root element
286
}
287
288
/**
289
* Style object interface for customizing redbox appearance
290
*/
291
interface RedBoxStyles {
292
redbox?: React.CSSProperties; // Main container styles (fixed position overlay)
293
message?: React.CSSProperties; // Error message text styles
294
stack?: React.CSSProperties; // Stack trace container styles
295
frame?: React.CSSProperties; // Individual stack frame styles
296
file?: React.CSSProperties; // Filename text styles
297
linkToFile?: React.CSSProperties; // File link styles
298
}
299
300
/**
301
* Default style values used by redbox-react
302
*/
303
const defaultStyles: RedBoxStyles = {
304
redbox: {
305
boxSizing: 'border-box',
306
fontFamily: 'sans-serif',
307
position: 'fixed',
308
padding: 10,
309
top: '0px',
310
left: '0px',
311
bottom: '0px',
312
right: '0px',
313
width: '100%',
314
background: 'rgb(204, 0, 0)',
315
color: 'white',
316
zIndex: 2147483647,
317
textAlign: 'left',
318
fontSize: '16px',
319
lineHeight: 1.2,
320
overflow: 'auto'
321
},
322
message: {
323
fontWeight: 'bold'
324
},
325
stack: {
326
fontFamily: 'monospace',
327
marginTop: '2em'
328
},
329
frame: {
330
marginTop: '1em'
331
},
332
file: {
333
fontSize: '0.8em',
334
color: 'rgba(255, 255, 255, 0.7)'
335
},
336
linkToFile: {
337
textDecoration: 'none',
338
color: 'rgba(255, 255, 255, 0.7)'
339
}
340
};
341
```
342
343
## Error Processing Features
344
345
### Source Map Support
346
347
Redbox React automatically processes stack traces through source maps when available:
348
349
- **Webpack Eval**: Automatically detects and handles webpack eval builds
350
- **Standard Eval**: Processes standard JavaScript eval patterns
351
- **Source Maps**: Uses `sourcemapped-stacktrace` for asynchronous source map processing
352
- **Error Stack Parser**: Parses JavaScript error stacks with `error-stack-parser`
353
354
### Stack Trace Enhancement
355
356
- **Clickable Links**: Stack trace entries become clickable links when editor scheme is configured
357
- **Line/Column Numbers**: Optionally display precise location information
358
- **File Path Processing**: Handles webpack loaders and absolute/relative paths
359
- **Fallback Handling**: Gracefully handles unparseable stack traces
360
361
## Integration Patterns
362
363
### React Transform Catch Errors
364
365
```javascript
366
// .babelrc configuration
367
{
368
"presets": ["react"],
369
"env": {
370
"development": {
371
"plugins": [
372
["react-transform", {
373
"transforms": [{
374
"transform": "react-transform-catch-errors",
375
"imports": ["react", "redbox-react"]
376
}]
377
}]
378
]
379
}
380
}
381
}
382
```
383
384
### React Hot Loader
385
386
```javascript
387
import { hot } from 'react-hot-loader/root';
388
import RedBox from 'redbox-react';
389
390
const App = () => {
391
// Your app component
392
};
393
394
export default hot(App);
395
```
396
397
### Webpack Integration
398
399
For accurate filenames in stack traces with Webpack:
400
401
```javascript
402
// webpack.config.js
403
module.exports = {
404
output: {
405
devtoolModuleFilenameTemplate: '/[absolute-resource-path]'
406
},
407
devtool: 'eval'
408
};
409
```
410
411
## Development Notes
412
413
- **Development Only**: This component should only be used in development environments
414
- **Portal Rendering**: RedBox renders outside the normal React tree to avoid CSS conflicts
415
- **Memory Management**: Components properly clean up DOM elements on unmount
416
- **Error Boundaries**: Compatible with React Error Boundaries for comprehensive error handling
417
- **Performance**: Lazy evaluation of source map processing to avoid blocking rendering