Skip to content

Instantly share code, notes, and snippets.

View mikaelbr's full-sized avatar

Mikael Brevik mikaelbr

View GitHub Profile
@mikaelbr
mikaelbr / own-jsx-2.js
Created October 8, 2019 19:14
Code for blogpost "Using JSX for your own lightweight declarative library": https://medium.com/@mikaelbrevik/using-jsx-for-your-own-lightweight-declarative-library-a773d3796475
const h1 = React.createElement("h1", null, "Hello, World");
@mikaelbr
mikaelbr / own-jsx-2.js
Created October 8, 2019 19:14
Code for blogpost "Using JSX for your own lightweight declarative library": https://medium.com/@mikaelbrevik/using-jsx-for-your-own-lightweight-declarative-library-a773d3796475
const h1 = <h1>Hello, World</h1>;
@mikaelbr
mikaelbr / own-jsx-1.js
Created October 8, 2019 19:12
Code for blogpost "Using JSX for your own lightweight declarative library"
{
"name": "jsx-demo",
"version": "1.0.0",
"main": "index.js",
"scripts": {
// Using the babel CLI specify our single file (could be pattern)
// and output in dist directory
"build": "babel index.js -d dist"
},
"devDependencies": {
function createUiFramework() {
const isEvent = k => k.startsWith("on");
const eventName = k => k.substr(2).toLowerCase();
const isString = s => typeof s === "string";
function attrs(el, props) {
for (let [k, val] of Object.entries(props)) {
if (isEvent(k)) {
el.addEventListener(eventName(k), val);
} else if (k === "class") {
const { button } = createUiFramework();
let initialState = { counter: 0 };
// Our application taking a state.
function app(state) {
// When we click on the button, rerender with new state where the counter is incremented
const onClick = () => render(app, { ...state, counter: state.counter + 1 });
return button({ type: "button", onClick }, `Increment ${state.counter}!`);
}
const { main, header, h1, h2 } = createUiFramework();
// Create my component with a similar signature
let myHeader = (props, children) =>
header(props, [children, h2("... a greeting blog")]);
// Use custom component
document.body.appendChild(
main({},
myHeader({ class: "header" }, h1("Hello, world!")))
const { button } = createUiFramework();
document.body.appendChild(
button(
{
type: "button",
onClick() {
console.log("Hello");
}
},
"Click me!"
// Check if key starts with `on`. If so, it is an event.
const isEvent = (k, v) => k.startsWith("on") && typeof v === "function";
// Removes `on` prefix to use it as event name
const eventName = k => k.substr(2).toLowerCase();
function attrs(el, props) {
for (let [k, val] of Object.entries(props)) {
// Extend attribute check with special case for events
if (isEvent(k)) {
const { button } = createUiFramework();
document.body.appendChild(
button(
{
type: "button",
onClick() {
console.log("Hello");
}
},
"Click me!"
console.log(
h1({ class: ["myHeader", "blue"] }, "Hello, World!")
);
//> <h1 class="myHeader blue">Hello, World!</h1>