31
loading...
This website collects cookies to deliver better user experience
<div id="foo">
Hello!
</div>
React.createElement("div", {
id: "foo"
}, "Hello!");
React.createElement
is a function that creates a virtual node.export {
createElement,
createElement as h,
} from './create-element';
createElement
function from Preact serves the same needs as React.createElement
. So the question is, why is it exported as h
as well?h
because it's a hypescript function. require 'markaby'
mab = Markaby::Builder.new
mab.html do
head { title "Boats.com" }
body do
h1 "Boats.com has great deals"
ul do
li "$49 for a canoe"
li "$39 for a raft"
li "$29 for a huge boot that floats and can fit 5 people"
end
end
end
puts mab.to_s
h
function allows doing essentially the same thing, but with different syntax.h = require("hyperscript")
h("div#foo", "Hello!")
h = require("hyperscript")
h("div#foo",
h("h1", "Hello from H1!", { style: { 'color': 'coral' } })
)
h
function does and why we need it, let's write our own version of it. Complete example can be found on codesanbox.render
function, that creates real DOM elements from our virtual nodes.const render = ({type, children, props}) => {
const element = document.createElement(type);
if (props) {
for (const prop in props) {
element.setAttribute(prop, props[prop]);
}
}
if (children) {
if (Array.isArray(children)) {
children.forEach(child => {
if (typeof child === 'string') {
element.innerText = child;
} else {
element.appendChild(render(child));
}
})
} else if (typeof children === 'string') {
element.innerText = children;
} else {
element.appendChild(render(children));
}
}
return element;
}
h
function.const h = (type, children, props) => {
let handledType = typeof type === 'string' ? type : 'div';
return {
type: handledType,
props,
children
}
}
h
function, render it with our render
function and mount the result to the DOM.const div = render(
h('div',
[
h('h1', 'Hello!', { id: 'foo' }),
h('h2', 'World!', { class: 'bar' })
],
)
);
document.querySelector('#app').appendChild(div);