Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A minimum custom renderer implementation using ReactFiber
/**
* @providesModule ReactConsole
*/
'use strict';
const colors = require('colors');
const ReactDOMFrameScheduling = require('ReactDOMFrameScheduling');
const ReactFiberReconciler = require('ReactFiberReconciler');
const sideEffect = (method, text) => console.log(colors[method](text));
const ConsoleRenderer = ReactFiberReconciler({
getRootHostContext() {
return {};
},
getChildHostContext() {
return {};
},
getPublicInstance(instance) {
return null;
},
createInstance(type, props) {
return {};
},
appendInitialChild(parentInstance, child) {},
finalizeInitialChildren(host, type, props) {
if (typeof props.children === 'string') {
sideEffect(type, props.children);
}
return false;
},
prepareUpdate(instance, type, oldProps, newProps) {
return {};
},
commitMount(instance, type, newProps) {},
commitUpdate(instance, updatePayload, type, oldProps, newProps) {
if (typeof newProps.children === 'string') {
if (newProps.children !== oldProps.children) {
sideEffect(type, newProps.children);
}
}
},
shouldSetTextContent(type, props) {},
resetTextContent(instance) {},
shouldDeprioritizeSubtree(type, props) {},
createTextInstance(text, rootContainerInstance, hostContext, internalInstanceHandle) {},
commitTextUpdate(textInstance, oldText, newText) {},
appendChild(parentInstance, child) {},
appendChildToContainer(parentInstance, child) {},
insertBefore(parentInstance, child, beforeChild) {},
insertInContainerBefore(container, child, beforeChild) {},
removeChild(parentInstance, child) {},
removeChildFromContainer(container, child) {},
prepareForCommit() {},
resetAfterCommit() {},
scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,
useSyncScheduling: true,
});
let root;
const ReactConsole = {
render(element, callback) {
if (!root) {
const container = {};
root = ConsoleRenderer.createContainer(container);
}
ConsoleRenderer.updateContainer(element, root, null, callback);
},
};
module.exports = ReactConsole;
const React = require('react');
const ReactConsole = require('ReactConsole');
const colors = require('colors');
describe('ReactConsole', () => {
it('should output text with colors into console', () => {
ReactConsole.render(
<div>
<red>Hello</red>
<yellow>World</yellow>
<cyan>React</cyan>
<rainbow>Custom Renderer!</rainbow>
</div>,
() => console.log(colors.inverse('##### Update ######'))
);
ReactConsole.render(
<div>
<green>Hello</green>
<yellow>World2</yellow>
<cyan>React</cyan>
</div>
);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment