Skip to content

Instantly share code, notes, and snippets.

@ibare
Last active July 4, 2023 15:37
Show Gist options
  • Save ibare/c736f63fba835c172e60aa98a996dada to your computer and use it in GitHub Desktop.
Save ibare/c736f63fba835c172e60aa98a996dada to your computer and use it in GitHub Desktop.
Custom React
/* @jsx createElement */
import { createElement, render, Component } from './react.js';
class Text extends Component {
render() {
return (
<span>L({this.props.v})</span>
);
}
}
function Hello(props) {
return <li className="item"><Text v={props.label} /></li>;
}
function App() {
let x = 10;
x = x ** x;
return (
<div>
<h1>hello world</h1>
<ul className="board" onClick={() => null}>
<Hello label="Hello balbla" />
<Hello label={`hello ${x}`} />
<Hello label="World 3" />
<Hello label="React 4" />
</ul>
</div>
);
}
render(<App />, document.getElementById("root"));
{
"name": "tiny-react",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "babel src -d build --plugins=@babel/proposal-class-properties -w",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.12.1",
"@babel/core": "^7.12.3",
"@babel/plugin-proposal-private-methods": "^7.12.1",
"@babel/preset-env": "^7.12.1",
"@babel/preset-react": "^7.12.5"
}
}
export class Component {
constructor(props) {
this.props = props;
}
}
function renderElement(node) {
if (typeof node === "string") {
return document.createTextNode(node);
}
if (node === undefined) return;
const $el = document.createElement(node.type);
node.children.map(renderElement).forEach((node) => {
$el.appendChild(node);
});
return $el;
}
export function render(vdom, container) {
container.appendChild(renderElement(vdom));
}
export function createElement(type, props, ...children) {
if (typeof type === "function") {
if (type.prototype instanceof Component) {
const comp = new type({ ...props, children });
return comp.render.call(comp);
} else {
return type.apply(null, [props, ...children]);
}
}
return { type, props, children };
}
@accidentlywoo
Copy link

아하! React.createElement(type, props, ...children) -> createElement(type, props, ...children) 이렇게 동작하는 군요! 감사합니다!

@ibare
Copy link
Author

ibare commented Nov 11, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment