### Install and Run Inferno Router Demo
Source: https://github.com/infernojs/inferno/blob/master/demo/inferno-router-demo/README.md
Navigate to the demo directory, install dependencies, and start the development server. Access the demo at the specified URL.
```sh
cd demo/inferno-router-demo
npm i
npm run dev
```
--------------------------------
### Install inferno-test-utils
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-test-utils/README.md
Install inferno and inferno-test-utils using npm.
```bash
npm install inferno --save
npm install inferno-test-utils --save-dev
```
--------------------------------
### Install Inferno v4 Dependencies
Source: https://github.com/infernojs/inferno/blob/master/documentation/v4-migration.md
When using inferno-compat, ensure all dependencies you use are installed separately to avoid duplicates. This example shows common inferno packages to install.
```bash
npm install --save inferno
npm install --save inferno-compat
npm install --save inferno-clone-vnode
npm install --save inferno-create-class
npm install --save inferno-create-element
```
--------------------------------
### Install inferno-create-element
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-create-element/readme.md
Install the inferno-create-element package using npm.
```bash
npm install inferno-create-element
```
--------------------------------
### Install inferno-server
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-server/README.md
Install the inferno and inferno-server packages using npm.
```bash
npm install inferno inferno-server
```
--------------------------------
### Install inferno-animation
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-animation/readme.md
Install the inferno-animation package using npm.
```bash
npm install inferno-animation
```
--------------------------------
### Install inferno-extras
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-extras/README.md
Install the inferno-extras package using npm.
```bash
npm install inferno-extras
```
--------------------------------
### Install createElement Package
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Install the inferno-create-element package for creating virtual DOM elements using the createElement API.
```sh
npm install --save inferno-create-element
```
--------------------------------
### Install inferno-vnode-flags
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-vnode-flags/README.md
Install the inferno-vnode-flags package using npm.
```bash
npm install --save inferno-vnode-flags
```
--------------------------------
### Install inferno-mobx
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
Install the inferno-mobx package using npm. Ensure mobx is also installed as a required dependency.
```bash
npm install --save inferno-mobx
```
```bash
npm install --save mobx
```
--------------------------------
### Install Inferno Addons (SSR)
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Install the inferno-server addon for server-side rendering capabilities.
```sh
npm install --save inferno-server
```
--------------------------------
### Install Lerna Globally
Source: https://github.com/infernojs/inferno/blob/master/CONTRIBUTING.md
Ensure Lerna is installed globally on your system before proceeding with development setup.
```bash
npm i -g lerna
```
--------------------------------
### Clean and Install Dependencies
Source: https://github.com/infernojs/inferno/blob/master/CONTRIBUTING.md
Commands to clean the project, install development dependencies, build TypeScript files, and run tests.
```bash
lerna clean
```
```bash
npm i
```
```bash
npm run build
```
```bash
npm run test
```
--------------------------------
### Install inferno-redux
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-redux/README.md
Install the inferno-redux package using npm.
```bash
npm install inferno-redux
```
--------------------------------
### Install Hyperscript Package
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Install the inferno-hyperscript package to use hyperscript syntax for creating virtual DOM elements.
```sh
npm install --save inferno-hyperscript
```
--------------------------------
### Install inferno-hydrate
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-hydrate/readme.md
Install the inferno-hydrate package using npm.
```bash
npm install inferno-hydrate
```
--------------------------------
### Basic Inferno Redux Usage Example
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-redux/README.md
Demonstrates setting up a Redux store and integrating it with an Inferno application using the Provider component. This example shows how to dispatch actions and access state within components.
```javascript
import { render } from 'inferno';
import { Router, Route, browserHistory } from 'inferno-router';
import { Provider } from 'inferno-redux';
import { createStore } from 'redux';
const store = createStore(function (state, action) {
switch (action.type) {
case 'CHANGE_NAME':
return {
name: action.name,
};
default:
return {
name: 'TOM',
};
}
});
class App extends Component {
render() {
return
);
}
}
class BasicComponent2 extends Component {
render() {
const store = this.context.store;
const state = store.getState();
return (
{state.name === 'Jerry' ? "You're a mouse!" : "You're a cat!"}
);
}
}
render(
,
container,
);
```
--------------------------------
### Render a Simple Component with JSX
Source: https://github.com/infernojs/inferno/blob/master/README.md
Basic example demonstrating how to render a component using JSX and the Inferno `render` function. Imports are required.
```jsx
import { render } from 'inferno';
const message = "Hello world";
render(
,
document.getElementById("app")
);
```
--------------------------------
### Install Inferno and Compatibility Packages
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-compat/README.md
Install the core Inferno package along with necessary compatibility and utility packages for full feature support.
```bash
npm install --save inferno
npm install --save inferno-compat
npm install --save inferno-clone-vnode
npm install --save inferno-create-element
```
--------------------------------
### Install Inferno Router
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-router/README.md
Install the inferno-router package using npm.
```bash
npm install inferno-router
```
--------------------------------
### Install JSX Babel Plugin
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Install the Babel plugin for Inferno to enable JSX syntax support during the build process.
```sh
npm install --save-dev babel-plugin-inferno
```
--------------------------------
### Example of createVNode usage
Source: https://github.com/infernojs/inferno/blob/master/README.md
Demonstrates creating a VNode for a `div` element with text content using `createVNode`, `createTextVNode`, and specifying flags.
```javascript
import { VNodeFlags, ChildFlags } from 'inferno-vnode-flags';
import { createVNode, createTextVNode, render } from 'inferno';
const vNode = createVNode(VNodeFlags.HtmlElement, 'div', 'example', createTextVNode('Hello world!'), ChildFlags.HasVNodeChildren);
//
Hello world!
render(vNode, container);
```
--------------------------------
### Clone and Build Inferno.js
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Steps to clone the Inferno.js repository, install dependencies, and perform a full build and test cycle.
```sh
git clone git@github.com:infernojs/inferno.git
cd inferno && npm i
npm run test:node
npm run build
npm run test:browser
```
--------------------------------
### Inferno MobX Integration Example
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
This example demonstrates how to integrate Inferno components with MobX stores using observerPatch. It shows various component types and their interaction with observable data, including comments on which components will and will not update.
```tsx
import {
MyComponentA,
MyComponentB,
MyComponentC,
MyComponentD,
MyComponentE,
MyComponentG,
MyComponentH,
MyComponentI,
MyComponentJ,
MyComponentK,
} from './MyComponent';
import { render } from 'inferno';
import { action, observable } from 'mobx';
const store = observable({ count: 0 });
render(
store.count} />
{' '}
{/* This component WILL NOT detect when count changes! */}
{' '}
{/* This component WILL NOT detect when count changes! */}
store.count} />{' '}
{/* Not an observer so no updating when count changes. */}
store.count} />{' '}
{/* Is an observer so it will update. */}
{' '}
{/* Works... BUT! when it unmounts there will be an error! */}
);
```
--------------------------------
### Install Inferno Addons (Routing)
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Install the inferno-router addon for handling routing within your Inferno application.
```sh
npm install --save inferno-router
```
--------------------------------
### Client-Side Routing with Inferno Router
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-router/README.md
Example of setting up client-side routing using BrowserRouter, Route, Link, and hooks like useLoaderData and useLoaderError.
```javascript
import { render } from 'inferno';
import {
BrowserRouter,
Route,
Link,
useLoaderData,
useLoaderError,
} from 'inferno-router';
const Home = () => (
Home
);
const About = (props) => {
const data = useLoaderData(props);
const err = useLoaderError(props);
return (
About
{data?.body || err?.message}
);
};
const Topic = ({ match }) => (
{match.params.topicId}
);
const Topics = ({ match }) => (
Topics
Rendering with React
Components
Props v. State
Please select a topic.
}
/>
);
const MyWebsite = () => (
Home
About
Topics
fetch(new URL('/api/about', BACKEND_HOST))}
/>
);
// Render HTML on the browser
render(, document.getElementById('root'));
```
--------------------------------
### Server-Side Rendering with Koa and Inferno Router
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-router/README.md
Example of server-side rendering using Koa, inferno-server, and StaticRouter for routing.
```jsx
import Koa from 'koa';
import { renderToString } from 'inferno-server';
import { Switch, StaticRouter, Route } from 'inferno-router';
const app = new Koa();
function Index({ children }) {
return (
Inferno
{children}
);
}
// Example routes
function Home() {
return
Welcome Home!
;
}
function Foo() {
return Bar;
}
function NotFound() {
return
404
;
}
const routes = (
);
// Server-side render
async function render(ctx, next) {
const context = {};
const content = renderToString(
{routes},
);
// This will contain the URL to redirect to if was used
if (context.url) {
return ctx.redirect(context.url);
}
ctx.type = 'text/html';
ctx.body = '\n' + content;
await next();
}
// Add infero render as middleware
app.use(render);
app.listen(8080, function () {
console.log('Listening on port ' + 8080);
});
```
--------------------------------
### Install Inferno Core Package
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Install the core Inferno package using npm. This is the primary package for building user interfaces with Inferno.
```sh
npm install --save inferno
```
--------------------------------
### Install Inferno Compatibility Package
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Install the inferno-compat package to help with compatibility when integrating Inferno into existing React applications. Refer to the inferno-compat documentation for usage details.
```sh
npm install --save-dev inferno-compat
```
--------------------------------
### Usage Example with Aliased React
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-compat/README.md
Demonstrates using a React component with aliased `react` and `react-dom` after setting up module aliases in Webpack or Browserify.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
class Foo extends React.Component {
propTypes = {
a: React.PropTypes.string.isRequired,
};
render() {
let { a, b, children } = this.props;
return
{children}
;
}
}
ReactDOM.render(test, document.getElementById('app'));
```
--------------------------------
### InfernoJS ForwardRef API Example
Source: https://github.com/infernojs/inferno/blob/master/documentation/v6-release.md
Demonstrates the `forwardRef` API in InfernoJS v6, enabling functional components to receive and forward refs to DOM elements. This example shows forwarding a ref to a `FancyButton` component.
```jsx
import { forwardRef, Component, render } from 'inferno';
const FancyButton = forwardRef((props, ref) => (
));
class Hello extends Component {
render() {
return (
{
if (btn) {
// btn variable is the button rendered from FancyButton
}
}}
>
Click me!
);
}
}
render(, container);
```
--------------------------------
### React component using inferno-compat
Source: https://context7.com/infernojs/inferno/llms.txt
Existing React code can be used with Inferno's engine by importing from inferno-compat. This example demonstrates an input component where onChange is mapped to onInput.
```jsx
// ExistingReactComponent.jsx — unchanged React code
import React, { Component, PureComponent } from 'react';
import ReactDOM from 'react-dom';
class MyWidget extends PureComponent {
state = { value: '' };
render() {
return (
{/* onChange works just like React — compat maps it to onInput */}
this.setState({ value: e.target.value })}
/>
You typed: {this.state.value}
);
}
}
ReactDOM.render(, document.getElementById('app'));
// Runs on Inferno's engine with React API — no source changes needed
```
--------------------------------
### Render a Component with Inferno.js
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Basic example of rendering a component using Inferno's render function. Assumes JSX is enabled via the Inferno JSX Babel Plugin.
```jsx
import { render } from 'inferno';
const message = 'Hello world';
render(, document.getElementById('app'));
```
--------------------------------
### Debug Tests in Browser
Source: https://github.com/infernojs/inferno/blob/master/CONTRIBUTING.md
Start a debug session for browser tests. Access the debugger by navigating to localhost:9876.
```bash
npm run test:browser:debug
```
--------------------------------
### Inferno Controlled Components Example
Source: https://github.com/infernojs/inferno/blob/master/README.md
Demonstrates controlled components for input, select, and textarea elements in Inferno. This ensures form data is managed by the component's state.
```javascript
import { Component } from 'inferno';
import { render } from 'inferno-dom';
class MyForm extends Component {
state = {
value: ''
};
handleChange = (e) => {
this.setState({ value: e.target.value });
};
render() {
return (
);
}
}
render(, document.getElementById('app'));
```
--------------------------------
### Using observerPatch with a Component
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
This example demonstrates how to use observerPatch to make an Inferno component observable with MobX. It shows a basic component rendering a counter and a button to increment it.
```jsx
{' '}
,
document.getElementById('components'),
);
```
```
--------------------------------
### InfernoJS Fragment Short Syntax Example
Source: https://github.com/infernojs/inferno/blob/master/documentation/v6-release.md
Demonstrates the short syntax `<>...>` for Fragments in InfernoJS v6, allowing components to return arrays of elements without a container DOM node. Requires the v6 babel-plugin-inferno.
```jsx
import { Component } from 'inferno';
class MyApplication extends Component {
render() {
/*
* This will render "Hi
Okay
"
* to location where MyApplication is used
* /
return (
<>
Hi
Okay
>
)
}
}
```
--------------------------------
### Hydrate SSR Content with inferno-hydrate
Source: https://github.com/infernojs/inferno/blob/master/documentation/v6-migration.md
Install 'inferno-hydrate' and use the 'hydrate' function on initial client load to re-use server-rendered HTML. Subsequent updates should use 'render'.
```jsx
import { render } from 'inferno';
import { hydrate } from 'inferno-hydrate';
// First time client is loaded, FE:
document.addEventListener('DOMContentLoaded', function(e) {
const element = document.getElementById('app');
hydrate(, element);
// Future updates should use render
render(, element);
});
```
--------------------------------
### InfernoJS CreateRef API Example
Source: https://github.com/infernojs/inferno/blob/master/documentation/v6-release.md
Shows how to use the `createRef` API in InfernoJS v6 to create a reference to a DOM element. The reference is stored in `this.element.current` after the component renders.
```jsx
import { Component, render, createRef } from 'inferno';
class Foobar extends Component {
constructor(props) {
super(props);
// Store reference somewhere
this.element = createRef(); // Returns object {current: null}
}
render() {
return (
Ok
);
}
}
render(, container);
```
--------------------------------
### Basic Usage with AnimatedAllComponent
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-animation/readme.md
Demonstrates how to use AnimatedAllComponent to animate list items on add/remove. Ensure the CSS is imported and applied correctly.
```javascript
import { Component } from 'inferno';
import { AnimatedAllComponent } from 'inferno-animation';
import './app.css';
// Animate on add/remove
class MyAnimated extends AnimatedAllComponent {
render() {
return
);
}
}
```
```css
@import '~inferno-animation/index.css';
ul {
list-style: none;
padding: 0;
margin: 0;
}
li.test {
box-sizing: border-box;
font-size: 2em;
background: #ddd;
border-bottom: 1px solid white;
}
```
--------------------------------
### Using observerPatch with Provider and inject
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
Demonstrates how to use observerPatch with Provider and inject for class components. Note that inject as a decorator alongside observerPatch is not supported. The recommended order is observerPatch before inject.
```tsx
import { Component } from 'inferno';
import { observerPatch, observerWrap, inject } from 'inferno-mobx';
interface CountStore {
readonly count: number;
}
// The class produced by inject will require the injected properties if required by the base class
class MyComponentA extends Component<{ countStore?: CountStore }> {
render({ countStore }: { countStore?: CountStore }) {
// If only the injected version will be used, casting is safe as an exception is thrown
// if the property is unavailable
const count = (countStore as CountStore).count.toString(); // unsafe if MyComponentA was exported
return
;
}
}
// The order of inject and observerPatch does not matter.
export const MyInjectedB = inject('countStore')(MyComponentB);
observerPatch(MyComponentB); // Works, but this order is more prone to the mistake shown below
class MyComponentC extends Component<{ countStore?: CountStore }> {
render({ countStore }: { countStore?: CountStore }) {
const count = (countStore as CountStore).count.toString();
return
Current Count: {count}
;
}
}
// Be sure to use observerPatch on the class, not the injected class.
// A warning message is output if you do this.
export const MyInjectedC = inject('countStore')(MyComponentC);
observerPatch(MyInjectedC); // WRONG! Should be: observerPatch(MyComponentC);
//Having observerPatch before inject lets tools detect this issue.
// Functional components with observerWrap
function MyComponentD({ countStore }: { countStore?: CountStore }) {
const count = (countStore as CountStore).count.toString();
return
Current Count: {count}
;
}
export const MyInjectedD = inject(observerWrap(MyComponentD));
```
--------------------------------
### Inferno Functional Component with defaultHooks
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Example of a functional component utilizing `defaultHooks` to define lifecycle methods like `onComponentShouldUpdate`.
```javascript
export function Static() {
return
1
;
}
Static.defaultHooks = {
onComponentShouldUpdate() {
return false;
},
};
```
--------------------------------
### Defining Routes with Inferno Router
Source: https://context7.com/infernojs/inferno/llms.txt
Demonstrates defining routes with URL parameters, data loaders, render props, and children. Ensure the BrowserRouter and Switch components wrap your routes for proper routing.
```jsx
import { render } from 'inferno';
import { BrowserRouter, Route, Switch } from 'inferno-router';
async function userLoader({ params }) {
const res = await fetch(`/api/users/${params.id}`);
return res; // inferno-router calls res.json() automatically
}
function UserProfile({ match, __loaderData__ }) {
const user = __loaderData__?.res;
if (!user) return null;
return
User: {user.name} (id={match.params.id})
;
}
render(
{/* Route with URL params and data loader */}
{/* Render prop variant */}
Current path: {location.pathname}
}
/>
{/* Children variant — always renders, receives match */}
{({ match }) => {match ? 'Matched!' : 'No match'}}
,
document.getElementById('app')
);
```
--------------------------------
### Create Fragment with createFragment and JSX
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Demonstrates creating identical fragments using both the `createFragment` API and JSX syntax. Use `createFragment` for programmatic creation, and JSX for declarative component structure.
```jsx
import { Fragment, render, createFragment } from 'inferno';
import { ChildFlags} from 'inferno-vnode-flags';
function Foobar() {
return (
{createFragment(
[
Ok
, 1],
ChildFlags.HasNonKeyedChildren,
'key1',
)}
Ok
1
);
}
render(, container);
```
--------------------------------
### Find All in VNode Tree Example
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-test-utils/README.md
Finds all VNodes in a VNode tree that satisfy a given predicate function. The predicate is called with each VNode instance.
```javascript
const vNodeTree = (
);
const predicate = (vNode) => vNode.type === SomeComponent;
const result = findAllInVNodeTree(vNodeTree, predicate);
```
--------------------------------
### Basic Usage of Inferno Hyperscript
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-hyperscript/README.md
Demonstrates how to import and use the `h` function from inferno-hyperscript to create a simple component with nested elements and dynamic content.
```javascript
var h = require('inferno-hyperscript');
module.exports = function ExampleComponent(props) {
return h('.example', [
h(
'a.example-link',
{
href: '#',
},
['Hello', props.whom, '!'],
),
]);
};
```
--------------------------------
### Find All in Rendered Tree Example
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-test-utils/README.md
Finds all VNodes in a rendered tree that satisfy a given predicate function. The predicate is called with each VNode instance.
```javascript
const vNodeTree = (
);
const renderedTree = render(vNodeTree, DOM);
const predicate = (vNode) => vNode.type === SomeComponent;
const result = findAllInRenderedTree(renderedTree, predicate);
```
--------------------------------
### Using observer with Inferno Component in v9
Source: https://github.com/infernojs/inferno/blob/master/documentation/v9-migration.md
Demonstrates how to achieve observable wrapping by extending an Inferno component, replacing the removed `inferno-create-class`.
```javascript
observer(
class MyCom extends Component {
componentWillReact() {
willReactCount++;
}
render() {
return (
);
}
},
);
```
--------------------------------
### Render into Container Example
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-test-utils/README.md
Renders a vNodeTree into a detached DOM element. This function requires a DOM environment, which can be provided by tools like JEST.
```javascript
const vNodeTree = (
);
const renderedTree = renderIntoContainer(vNodeTree);
```
--------------------------------
### Quick Browser Test Commands for Inferno.js
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Commands to speed up the browser testing process during development by compiling only necessary packages.
```sh
npm run quick-test:browser # Compiles all packages and runs browser tests
```
```sh
npm run quick-test:browser-inferno # Only compiles the inferno package and runs browser tests
```
```sh
npm run quick-test:browser-debug # Compiles all packages and runs browser tests with "debug"
```
--------------------------------
### Scry Rendered DOM Elements With Tag Example
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-test-utils/README.md
Returns an array of DOM elements within a rendered tree that match the specified tag name.
```javascript
const vNodeTree = (
Heading
Paragraph One
Paragraph Two
Paragraph Three
);
const renderedTree = render(vNodeTree, DOM);
const result1 = scryRenderedDOMElementsWithTag(renderedTree, 'h1');
const result3 = scryRenderedDOMElementsWithTag(renderedTree, 'p');
const result4 = scryRenderedVNodesWithType(renderedTree, 'span'); // Empty array
```
--------------------------------
### cloneVNode
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Clones and returns a new Inferno VNode using an existing VNode as a starting point. It allows merging new props and replacing children.
```APIDOC
## `cloneVNode`
### Description
Clones and returns a new Inferno `VNode` using a `VNode` as the starting point. The resulting `VNode` will have the original `VNode`'s props with the new props merged in shallowly. New children will replace existing children. `key` and `ref` from the original `VNode` will be preserved.
### Signature
`cloneVNode(vNode, [props], [...children])`
### Parameters
- `vNode` (VNode): The VNode to clone.
- `props` (Object): Optional. New props to merge into the cloned VNode.
- `children` (Array): Optional. New children to replace the existing children.
```
--------------------------------
### SWC Plugin for Inferno JSX Compilation
Source: https://github.com/infernojs/inferno/blob/master/README.md
Use the SWC plugin to compile TSX and JSX for Inferno applications. Ensure SWC is installed and configured in your project.
```javascript
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true
},
"transform": {
"optimizer": {
"react": true
}
}
},
"plugin": [
"@swc/plugin-inferno"
]
}
```
--------------------------------
### Create and Render an Inferno Element
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-create-element/readme.md
Use `createElement` to create a virtual DOM element and `render` to display it in the DOM. Ensure you have imported both functions.
```javascript
import { createElement } from 'inferno-create-element';
import { render } from 'inferno';
render(
createElement('div', { className: 'test' }, "I'm a child!"),
document.getElementById('app'),
);
```
--------------------------------
### Format Code with Prettier
Source: https://github.com/infernojs/inferno/blob/master/CONTRIBUTING.md
Run this command before committing changes to ensure code formatting adheres to project standards.
```bash
npm run prettier
```
--------------------------------
### `renderToString` / `renderToStaticMarkup` — package `inferno-server`
Source: https://context7.com/infernojs/inferno/llms.txt
Synchronously renders a virtual node tree to an HTML string on the server. `renderToStaticMarkup` is an alias (Inferno does not add `data-root` attributes). Calls `componentWillMount` and `getChildContext` on class components during SSR.
```APIDOC
## `renderToString` / `renderToStaticMarkup` — package `inferno-server`
Synchronously renders a virtual node tree to an HTML string on the server. `renderToStaticMarkup` is an alias (Inferno does not add `data-root` attributes). Calls `componentWillMount` and `getChildContext` on class components during SSR.
```js
// server.js (Node / Express)
import express from 'express';
import { renderToString } from 'inferno-server';
import { StaticRouter } from 'inferno-router';
const app = express();
app.get('*', (req, res) => {
const context = {};
const html = renderToString(
);
if (context.url) {
return res.redirect(301, context.url);
}
res.send(`
My App
${html}
`);
});
app.listen(3000);
```
```
--------------------------------
### Find DOM Node with inferno-extras
Source: https://github.com/infernojs/inferno/blob/master/documentation/v6-migration.md
The 'dom' property on VNodes is no longer always populated. Use the 'findDOMNode' helper from 'inferno-extras' to get the DOM node for a component instance.
```jsx
import { Component } from 'inferno';
import { findDOMNode } from 'inferno-extras';
class Example extends Component {
componentDidMount() {
// element equals "
Okay
"
const element = findDOMNode(this);
}
render() {
return
Okay
;
}
}
```
--------------------------------
### createElement
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Creates an Inferno VNode using a similar API to React's `createElement()`. This is a convenient way to define UI elements programmatically.
```APIDOC
## createElement
### Description
Creates an Inferno VNode using a similar API to that found with React's `createElement()`.
### Usage
```javascript
import { createElement } from 'inferno-create-element';
const vNode = createElement(
'div',
{ className: 'my-class' },
'Hello, Inferno!'
);
```
### Parameters
- `type` (string | Component): The type of element to create (e.g., 'div', 'span', or a component).
- `props` (object, optional): An object containing properties for the element (e.g., className, onClick).
- `...children` (any): Child nodes or content to be rendered within the element.
```
--------------------------------
### Define an ES6 Class Component in Inferno.js
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Example of defining a stateful ES6 class component in Inferno.js, similar to React. Includes a constructor for state initialization and a render method.
```jsx
import { render, Component } from 'inferno';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
}
render() {
return (
Header!
Counter is at: {this.state.counter}
);
}
}
render(, document.getElementById('app'));
```
--------------------------------
### Browserify Configuration with Aliasify
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-compat/README.md
Configure `aliasify` in your `package.json` to alias `react` and `react-dom` to `inferno-compat` for Browserify.
```json
{
// ...
"aliasify": {
"aliases": {
"react": "inferno-compat",
"react-dom": "inferno-compat"
}
}
// ...
}
```
--------------------------------
### Debug Tests in NodeJS
Source: https://github.com/infernojs/inferno/blob/master/CONTRIBUTING.md
Initiate a debug session for NodeJS tests. Open Chrome and navigate to chrome://inspect/#devices to connect.
```bash
npm run debug
```
--------------------------------
### JSX compile-time optimization flags
Source: https://context7.com/infernojs/inferno/llms.txt
Utilize special boolean props starting with '$' to set ChildFlags and VNodeFlags at compile time, optimizing known-shape children and eliminating runtime normalization.
```jsx
import { render, Component, createTextVNode } from 'inferno';
class FastList extends Component {
render() {
const items = this.props.items; // always an array of elements, never nested
return (
// $HasKeyedChildren: children are a flat array of keyed vNodes — skip normalization
{items.map(item => (
{item.label}
))}
);
}
}
// $HasVNodeChildren: single VNode child, no normalization needed
function Wrapper({ child }) {
return
{child}
;
}
// $ReCreate: always destroy and re-create this VNode (never diff)
function Modal({ content }) {
return
{content}
;
}
render(
,
document.getElementById('app')
);
```
--------------------------------
### Avoiding Multiple observerPatch Calls on a Class
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
Warns against calling observerPatch more than once on the same class. This example shows the correct way to apply observerPatch once and then illustrates the incorrect practice of calling it multiple times.
```tsx
export class MyComponentK extends Component<{ countStore: CountStore }> {
render({ countStore }: { countStore: CountStore }) {
return
Current Count: {countStore.count.toString()}
;
}
}
observerPatch(MyComponentK);
observerPatch(MyComponentK); // NEVER call more than once per class!
```
--------------------------------
### Rendering components with Provider and inject
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
Sets up the MobX Provider and renders injected Inferno components. Note that direct properties override injection, and only properties available when Provider mounts are injected.
```tsx
import {
MyInjectedA,
MyInjectedB,
MyInjectedC,
MyInjectedD,
} from './MyInjected';
import { render } from 'inferno';
import { Provider } from 'inferno-mobx';
import { action, observable } from 'mobx';
const store = observable({ count: 0 });
const store2 = observable({ count: 0 });
// NOTE: Do not use Provider and inject for trivial cases like this in real code.
render(
{' '}
{/* This one will not update as MyComponentC was not made into an observer. */}
{' '}
{/* Will not update as direct properties override injection */}
,
document.getElementById('root'),
);
```
--------------------------------
### AnimatedComponent / componentDidAppear / componentWillDisappear / componentWillMove
Source: https://context7.com/infernojs/inferno/llms.txt
CSS-class-based animation system. Extend AnimatedComponent to get automatic enter/leave animations driven by an animation prop. Standalone functions can be used in custom components.
```APIDOC
## AnimatedComponent / componentDidAppear / componentWillDisappear / componentWillMove — package `inferno-animation`
CSS-class-based animation system. Extend `AnimatedComponent` to get automatic enter/leave animations driven by an `animation` prop (string prefix or `{ start, active, end }` class object). Standalone `componentDidAppear`, `componentWillDisappear`, `componentWillMove` functions can be used in custom class components or functional components via `componentDidAppear`/`componentWillDisappear` lifecycle props.
```jsx
import { render } from 'inferno';
import { AnimatedComponent } from 'inferno-animation';
// CSS (animation.css):
// .fade-enter { opacity: 0; }
// .fade-enter-active { transition: opacity 300ms ease; }
// .fade-enter-end { opacity: 1; }
// .fade-leave { opacity: 1; }
// .fade-leave-active { transition: opacity 300ms ease; }
// .fade-leave-end { opacity: 0; }
class FadeBox extends AnimatedComponent {
render() {
return
{this.props.children}
;
}
}
class App extends Component {
state = { show: true };
render() {
return (
{this.state.show && (
// animation="fade" → uses class prefix "fade-enter", "fade-leave", etc.
Hello, animated world!
)}
);
}
}
render(, document.getElementById('app'));
```
```
--------------------------------
### observerPatch for Components Depending on MobX Observables
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
Highlights that only components directly depending on MobX observables need to be observers. This example shows a component that uses an observer child component, and the parent itself does not need observerPatch.
```tsx
export class MyComponentG extends Component<{ countStore: CountStore }> {
render({ countStore }: { countStore: CountStore }) {
// MyComponentB is an observer and will re-render when countStore.count changes.
return (
countStore.count} />
);
}
}
// observerPatch(MyComponentG) is not needed and would add overhead for no reason.
```
--------------------------------
### Create and Render Charts with Inferno
Source: https://github.com/infernojs/inferno/blob/master/scripts/fakedom/viewer.html
This snippet initializes Chart.js to display memory and CPU statistics fetched from a JSON file. It defines a reusable function to create charts, handling data processing and chart configuration.
```javascript
const memChart = document.getElementById('memChart');
const cpuChart = document.getElementById('cpuChart');
function createChart(stats, el, type, scales) {
const dataSets = [];
let labels = [];
for (let i = 0; i < stats[0].length; i++) {
labels.push(i);
}
for (let r = 0; r < stats.length; r++) {
const statsRow = stats[r];
const dataSet = {
label: 'base' + r,
data: [],
fill: false,
borderColor: 'rgb(75, 192, 192)',
borderWidth: 1,
radius: 0,
tension: 0.1
};
for (const testStat of statsRow) {
dataSet.data.push(testStat[type]);
}
dataSets.push(dataSet);
}
const data = {
labels: labels,
datasets: dataSets
};
new Chart(el, {
type: 'line',
data: data,
options: {
animation: false,
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Line Chart'
}
},
scales
},
});
}
;(async function() {
const stats = await (await fetch('/scripts/fakedom/results/inferno_base_line.json')).json();
createChart(stats, memChart, 'memory');
createChart(stats, cpuChart, 'cpu', {
y: {
min: -0.5,
max: 30
}
});
}());
```
--------------------------------
### Scry Rendered DOM Elements With Class Example
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-test-utils/README.md
Returns an array of DOM elements within a rendered tree that match the provided class names. Class names can be a space-separated string or an array of strings.
```javascript
const vNodeTree = (
);
const renderedTree = render(vNodeTree, DOM);
const result1 = scryRenderedDOMElementsWithClass(renderedTree, 'inner');
const result2 = scryRenderedDOMElementsWithClass(renderedTree, 'inner one');
const result3 = scryRenderedDOMElementsWithClass(renderedTree, [
'inner',
'two',
]);
const result4 = scryRenderedDOMElementsWithClass(renderedTree, 'three'); // Empty array
```
--------------------------------
### Inferno CDN Link (unpkg.com)
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno/README.md
Access pre-bundled Inferno files for browser consumption via unpkg.com.
```html
https://unpkg.com/inferno@latest/dist/inferno.min.js
```
--------------------------------
### Hooking up Animation Hooks to Functional Components
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-animation/readme.md
Shows how to attach animation hooks to functional components using provided helper methods. Always use these helpers for potential future optimizations.
```javascript
import {
componentDidAppear,
componentWillDisappear,
componentWillMove,
} from 'inferno-animation';
...
;
```
--------------------------------
### Provide MobX Stores using Provider
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
Set up MobX stores using `observable` and provide them to the application using the `Provider` component from `inferno-mobx`. This makes stores accessible to injected components.
```javascript
import { render } from 'inferno';
import { Provider } from 'inferno-mobx';
import { observable } from 'mobx';
import MyComponent from './MyComponent';
const englishStore = observable({
title: 'Hello World',
});
const frenchStore = observable({
title: 'Bonjour tout le monde',
});
render(
,
document.getElementById('root'),
);
```
--------------------------------
### Basic observerPatch Usage with Class Component
Source: https://github.com/infernojs/inferno/blob/master/packages/inferno-mobx/README.md
Pass a class component to observerPatch to enable automatic re-rendering when MobX observables read by the component's render method are modified. This example shows a component that reads a 'count' property from a store.
```tsx
import { Component } from 'inferno';
import { observerPatch } from 'inferno-mobx';
interface CountStore {
readonly count: number;
}
export class MyComponentA extends Component<{ countStore: CountStore }> {
render({ countStore }: { countStore: CountStore }) {
return