Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created September 20, 2019 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/49c1de35145b560a829c0fe0fb6e6577 to your computer and use it in GitHub Desktop.
Save ryanflorence/49c1de35145b560a829c0fe0fb6e6577 to your computer and use it in GitHub Desktop.
import React from 'react';
import { JSDOM } from 'jsdom';
const { document } = new JSDOM('').window;
function App() {
const [count, setCount] = useState(false);
const [error, setError] = useState(null);
const subtract = () => setCount(count - 1);
const add = () => setCount(count + 1);
return (
<div>
<h1>Example</h1>
<button onClick={subtract}>-</button>
{count}
<button onClick={add}>+</button>
{error && <p>Oops!</p>}
</div>
);
}
function useState(initial) {
return [initial, () => {}];
}
function ReactDOMRender(element, rootNode) {
const node = recurseTree(element);
rootNode.appendChild(node)
}
function recurseTree(element, parent) {
if (element && typeof element.type === 'function') {
return recurseTree(element.type(element.props), parent);
}
let node;
if (element === null) {
node = document.createComment('empty');
} else if (typeof element !== 'object') {
node = document.createTextNode(element);
} else {
node = document.createElement(element.type);
const { children } = element.props;
if (children) {
const childElements = Array.isArray(children) ? children : [children];
childElements.forEach(child => {
recurseTree(child, node);
});
}
}
if (parent) {
parent.appendChild(node);
}
return node;
}
////////////////////////////////////////////////////////////
const root = document.createElement('div')
ReactDOMRender(<App />, root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment