One of the most interesting features of Symbiote.js is very simple way to bind handlers and dynamic data to a previously rendered server-side markup (aka hydration). Let's dive into how it works.
You can render your HTML-code with any server-side template engine you prefer.
The following example uses standard Template Literal in Node.js environment, to define simple HTML-chunk, using html tag helper:
import html from '@symbiotejs/symbiote/core/html.js';
export default html`
<my-component>
<h2 ${{textContent: 'count'}} ref="count">0</h2>
<button ${{onclick: 'increment'}}>Click me!</button>
</my-component>
`;
This will be transformed to the following HTML:
<my-component>
<h2 ref="count" bind="textContent: count">0</h2>
<button bind="onclick: increment">Click me!</button>
</my-component>
Initial value of the count property could be defined in the server-side context. Now it is 0.
Then, all you need to make magic happen - is to set the ssrMode flag to true in your client-side component code:
import { Symbiote } from '@symbiotejs/symbiote';
class MyComponent extends Symbiote {
ssrMode = true;
init$ = {
count: 0,
increment: () => {
this.$.count++;
},
}
renderCallback() {
// Initialize the count property from the server-side rendered HTML:
this.$.count = parseFloat(this.ref.count.textContent);
}
}
MyComponent.reg('my-component');
This approach allows to build complex hybrid web-applications and well suitable for the JSDA-stack solutions.