@ryanmorr/carbon
v1.0.1
Published
The building blocks of UI
Downloads
72
Maintainers
Readme
carbon
The building blocks of UI
Install
Download the CJS, ESM, UMD versions or install via NPM:
npm install @ryanmorr/carbon
Usage
Carbon is a tiny, low-level, no-nonsense, virtual DOM implementation that offers robust and efficient DOM rendering:
import { h, text, render } from '@ryanmorr/carbon';
const setCount = (count) => {
render(document.body,
h('div', [
h('p', text('Count: ' + count)),
h('button', {onclick: () => setCount(count + 1)}, text('Increment')),
])
);
};
setCount(0);
Render a single element and return the element reference:
const element = render(parent,
h('div')
);
Render an array of elements and return an array of the element references:
const elements = render(parent, [
h('span'),
h('span'),
h('span')
]);
Set attributes using key/value pairs of an object:
render(parent,
h('img', {
src: '/path/to/file',
alt: 'Image description'
})
);
Set an element class name with a string, array, or object:
render(parent, [
h('div', {class: 'foo'}),
h('div', {class: ['foo', 'bar']}),
h('div', {class: {foo: true, bar: false}})
]);
Set CSS styles with a string or object:
render(parent, [
h('div', {style: 'width: 100px; height: 100px; background-color: red'}),
h('div', {style: {width: '100px', height: '100px', backgroundColor: 'red'}})
]);
Set CSS custom properties:
render(parent,
h('section', {style: {'--color': 'red'}},
h('p', {color: 'var(--color)'}, 'Hello World'),
)
);
Set event listeners as attributes indicated by a prefix of "on":
render(parent,
h('div', {
onclick: (e) => console.log('clicked')
})
);
Use the text
function to explicitly create virtual text nodes:
render(parent,
h('h1', text('Hello World'))
);
Add a unique key
to sibling elements to facilitate efficient reordering:
render(parent,
h('ul',
h('li', {key: 'foo'}, 'foo'),
h('li', {key: 'bar'}, 'bar'),
h('li', {key: 'baz'}, 'baz'),
h('li', {key: 'qux'}, 'qux')
)
);
Supports SVG elements:
render(parent,
h('svg', {width: 200, height: 200},
h('circle', {cx: 50, cy: 50, r: 40, fill: 'yellow'})
)
);
Supports stateless functional components:
const Component = ({id, children}) => {
return h('div', {id}, children);
};
render(parent,
h(Component, {id: 'foo'}, text('Hello World'))
);
Supports JSX syntax:
render(parent,
<div>
<h1>{title}</h1>
<button onclick={handleEvent}>Click Me</button>
</div>
);
Carbon will automatically recycle and patch over pre-existing DOM nodes, such as those generated from server-side rendered HTML.
License
This project is dedicated to the public domain as described by the Unlicense.