0
# Preact Compat
1
2
Preact Compat is a React compatibility layer for Preact that provides the same exports as `react` and `react-dom`. It enables React-based modules to work with Preact without code changes, offering a complete React 15.1.0 API implementation optimized for Preact 8.x and prior versions.
3
4
## Package Information
5
6
- **Package Name**: preact-compat
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install preact-compat`
10
- **Peer Dependencies**: `preact <10`
11
12
## Core Imports
13
14
```javascript
15
import React from 'preact-compat'; // Default export with all APIs
16
import { Component, render, createElement } from 'preact-compat'; // Named exports
17
```
18
19
For CommonJS:
20
21
```javascript
22
const React = require('preact-compat'); // Default export
23
const { Component, render, createElement } = require('preact-compat'); // Named exports
24
```
25
26
## Basic Usage
27
28
```javascript
29
import React, { Component } from 'preact-compat';
30
import { render } from 'preact-compat';
31
32
// Standard React component patterns work unchanged
33
class MyComponent extends Component {
34
state = { count: 0 };
35
36
increment = () => {
37
this.setState({ count: this.state.count + 1 });
38
};
39
40
render() {
41
return (
42
<div>
43
<p>Count: {this.state.count}</p>
44
<button onClick={this.increment}>Increment</button>
45
</div>
46
);
47
}
48
}
49
50
// Render to DOM (same as ReactDOM.render)
51
render(<MyComponent />, document.getElementById('root'));
52
```
53
54
## Architecture
55
56
Preact Compat provides complete React API compatibility through several key components:
57
58
- **Main Module**: Core React APIs including createElement, Component, render, and lifecycle methods
59
- **Server Module**: Server-side rendering capabilities with renderToString and renderToStaticMarkup
60
- **Library Modules**: Specialized React features like createClass, DOM factories, immutability helpers, and transition groups
61
- **Context System**: Full React context API support via preact-context
62
- **PropTypes Integration**: Runtime type checking through prop-types library
63
- **Performance Optimizations**: Pure render mixins and shallow comparison utilities
64
65
## Capabilities
66
67
### Core React API
68
69
Primary React compatibility layer providing all essential React APIs including component system, virtual DOM, lifecycle methods, and rendering functions.
70
71
```javascript { .api }
72
// Component System
73
class Component {
74
constructor(props, context);
75
setState(partialState, callback);
76
forceUpdate(callback);
77
render();
78
}
79
80
class PureComponent extends Component {}
81
82
// Element Creation
83
function createElement(type, props, ...children);
84
function cloneElement(element, props, ...children);
85
function createFactory(type);
86
function isValidElement(object);
87
function createPortal(vnode, container);
88
89
// Rendering
90
function render(vnode, parent, merge);
91
function hydrate(vnode, parent);
92
function findDOMNode(component);
93
function unmountComponentAtNode(container);
94
```
95
96
[Core React API](./core-api.md)
97
98
### Server-Side Rendering
99
100
Server-side rendering capabilities for generating HTML strings from components, supporting both static markup and hydration patterns.
101
102
```javascript { .api }
103
function renderToString(vnode);
104
function renderToStaticMarkup(vnode);
105
```
106
107
[Server-Side Rendering](./server-rendering.md)
108
109
### Children Utilities
110
111
Comprehensive utilities for working with component children, providing safe iteration and manipulation methods.
112
113
```javascript { .api }
114
const Children = {
115
map(children, fn, ctx);
116
forEach(children, fn, ctx);
117
count(children);
118
only(children);
119
toArray(children);
120
};
121
```
122
123
[Children Utilities](./children-utilities.md)
124
125
### Context API
126
127
Full React context system for sharing data between components without explicit prop passing.
128
129
```javascript { .api }
130
function createContext(defaultValue);
131
132
interface Context<T> {
133
Provider: ComponentClass<{value: T, children?: ComponentChildren}>;
134
Consumer: ComponentClass<{children: (value: T) => ComponentChildren}>;
135
}
136
```
137
138
[Context API](./context-api.md)
139
140
### Refs System
141
142
Reference system for accessing DOM nodes and component instances directly.
143
144
```javascript { .api }
145
function createRef();
146
147
interface RefObject<T> {
148
current: T | null;
149
}
150
```
151
152
[Refs System](./refs-system.md)
153
154
### Legacy React APIs
155
156
Support for legacy React patterns including createClass, DOM factories, and deprecated lifecycle methods for backward compatibility.
157
158
```javascript { .api }
159
function createClass(spec);
160
const DOM = {
161
a: ElementFactory,
162
div: ElementFactory,
163
span: ElementFactory,
164
// ... all HTML elements
165
};
166
```
167
168
[Legacy React APIs](./legacy-apis.md)
169
170
### Immutability Helpers
171
172
Data update utilities for managing immutable state transformations safely and efficiently.
173
174
```javascript { .api }
175
function update(object, spec);
176
177
interface UpdateSpec {
178
$set?: any;
179
$merge?: object;
180
$push?: Array<any>;
181
$unshift?: Array<any>;
182
$splice?: Array<Array<any>>;
183
$apply?: (value: any) => any;
184
}
185
```
186
187
[Immutability Helpers](./immutability-helpers.md)
188
189
### Transition Groups
190
191
Animation and transition components for managing component lifecycle animations and CSS transitions.
192
193
```javascript { .api }
194
class TransitionGroup extends Component {}
195
class CSSTransitionGroup extends Component {}
196
```
197
198
[Transition Groups](./transition-groups.md)
199
200
### Performance Tools
201
202
Development and performance utilities including pure render mixins and performance measurement tools.
203
204
```javascript { .api }
205
const PureRenderMixin = {
206
shouldComponentUpdate(nextProps, nextState);
207
};
208
209
const ReactPerf = {
210
start();
211
stop();
212
getLastMeasurements();
213
printInclusive();
214
printExclusive();
215
printWasted();
216
};
217
```
218
219
[Performance Tools](./performance-tools.md)
220
221
### PropTypes Validation
222
223
Runtime type checking for React props, providing development-time validation and error reporting.
224
225
```javascript { .api }
226
const PropTypes = {
227
// Primitive types
228
array: Validator;
229
bool: Validator;
230
func: Validator;
231
number: Validator;
232
object: Validator;
233
string: Validator;
234
symbol: Validator;
235
236
// Renderable types
237
node: Validator;
238
element: Validator;
239
240
// Collections
241
arrayOf(validator: Validator): Validator;
242
objectOf(validator: Validator): Validator;
243
244
// Specific values
245
oneOf(values: Array<any>): Validator;
246
oneOfType(validators: Array<Validator>): Validator;
247
248
// Complex objects
249
shape(spec: {[key: string]: Validator}): Validator;
250
exact(spec: {[key: string]: Validator}): Validator;
251
252
// Instances
253
instanceOf(constructor: Function): Validator;
254
255
// Any type (no validation)
256
any: Validator;
257
};
258
259
interface Validator {
260
isRequired: Validator;
261
(props: object, propName: string, componentName: string): Error | null;
262
}
263
```
264
265
**Usage:**
266
267
```javascript
268
import { PropTypes } from 'preact-compat';
269
270
class MyComponent extends Component {
271
static propTypes = {
272
name: PropTypes.string.isRequired,
273
age: PropTypes.number,
274
items: PropTypes.arrayOf(PropTypes.string),
275
config: PropTypes.shape({
276
debug: PropTypes.bool,
277
level: PropTypes.oneOf(['info', 'warn', 'error'])
278
})
279
};
280
281
render() {
282
return <div>Hello {this.props.name}</div>;
283
}
284
}
285
```
286
287
*Note: PropTypes validation only runs in development mode when `process.env.NODE_ENV !== 'production'`.*
288
289
## Types
290
291
```javascript { .api }
292
// Core types used throughout the API
293
type ComponentChildren = VNode<any> | object | string | number | boolean | null | undefined | Array<ComponentChildren>;
294
295
interface VNode<P = {}> {
296
type: ComponentType<P> | string;
297
props: P & { children?: ComponentChildren };
298
key: string | number | null;
299
ref: Ref<any> | null;
300
}
301
302
interface ComponentClass<P = {}> {
303
new (props: P, context?: any): Component<P, any>;
304
defaultProps?: Partial<P>;
305
contextTypes?: ValidationMap<any>;
306
childContextTypes?: ValidationMap<any>;
307
}
308
309
type ComponentType<P = {}> = ComponentClass<P> | ((props: P) => VNode<any>);
310
311
type Ref<T> = ((instance: T | null) => void) | RefObject<T>;
312
```