Template literals are mostly found in vue js, but this library makes
it possible that you can use template literals in your react app.
It
has the same declarative API like React, but instead of working with
Virtual DOM, it uses tagged template literals and HTML's template tag
for faster rendering and updates.
The most interesting part that got me excited.
It
divides the HTML to be rendered into static and dynamic parts, and in
next render, it has to compare the values of only dynamic parts and
apply the changes optimally to the connected DOM.
It's unlike the
VDOM which compares the whole last rendered VDOM to the new VDOM (which
has both static and dynamic parts) to derive the optimal changes that
are required on the actual DOM.
This is a game changer, and the speed is compared to that of nextjs, even the developer has to code on well JSX.
The babel-plugin-brahmos transforms JSX into tagged template literals which are optimized for render/updates and the output size.
Check this two examples out, one with the virtual dom, which will be transformed to template literalls.
class TodoList extends Component {
state = { todos: [], text: '' };
setText = (e) => {
this.setState({ text: e.target.value });
};
addTodo = () => {
let { todos, text } = this.state;
this.setState({
todos: todos.concat(text),
text: '',
});
};
render() {
const { todos, text } = this.state;
return (
<form className="todo-form" onSubmit={this.addTodo} action="javascript:">
<input value={text} onChange={this.setText} />
<button type="submit">Add</button>
<ul className="todo-list">
{todos.map((todo) => (
<li className="todo-item">{todo}</li>
))}
</ul>
</form>
);
}
}
The transformation
class TodoList extends Component {
state = { todos: [], text: '' };
setText = (e) => {
this.setState({ text: e.target.value });
};
addTodo = () => {
let { todos, text } = this.state;
this.setState({
todos: todos.concat(text),
text: '',
});
};
render() {
const { todos, text } = this.state;
return html`
<form class="todo-form" ${{ onSubmit: this.addTodo }} action="javascript:">
<input ${{ value: text }} ${{ onChange: this.setText }} />
<button type="submit">Add</button>
<ul class="todo-list">
${todos.map((todo) =>
html`
<li class="todo-item">${todo}</li>
`(),
)}
</ul>
</form>
`;
}
}
With
the tagged template literal we get a clear separating of the static and
dynamic part. And on updates it needs to apply changes only on the
changed dynamic parts.
How to setup a Brahmos UI app.
Step 1: install the brahmos library globally
npm install -g create-brahmos-app
Scaffold a new brahmos app
create-brahmos-app my-brahmos-app
Start the app
npm start
Build the app
npm run build
Eject the app
npm run eject