$render utility
$render adds JSX to the DOM with the #root id
or a target id
of a component. It makes using JSX directly in the browser without a virtual DOM possible.
$render(Component, props?optional);
Rendering
It is adding JSX to the DOM that happens in the browser without any user interactions with the DOM elements.
- Rendering without props
function Profile() {
return `
<div id="1">
Ayobami Ogundiran
</div>
`;
}
$render(Profile); //without props
- Rendering with props
const item = {
id: 1,
person: {},
children: { a: "No" }
}
function Profile(item) {//without default value
return `
<div
id="${item.id}"
person=${stringify(item.person)}>
${item.children.a}
</div>
`;
}
$render(Profile, item);//with props
Re-rendering
It is adding JSX to the DOM that happens in the browser when you interact with the DOM.
Note: A re-renderable component must have a wrapping div
tag with an ID
.
- Self-contained re-rendering
const Shuffle = (status=false) => {
return `
<div id="shuffle">
<button class="btn-icon toggle">
<span
class="material-symbols-rounded ${status ? 'active': ''}"
onclick="$render(Shuffle, ${!status})"
>shuffle ${status} </span>
</button>
</div>
`;
}
$render(Shuffle);
In the code above, you would notice we use $render(Shuffle, ${!status})
to make the Shuffle
itself re-render whenever the shuffle button is clicked.
- Re-rendering from a controller
You might need to perform some operations you don't want to tie to a component, then you can create reusable utilities.
- Add
appUtils.js
to theHTML
page.
function toggle (status) {
$render(Shuffle, !status);
}
const Shuffle = (status=false) => {
return `
<div id="shuffle">
<button class="btn-icon toggle">
<span
class="material-symbols-rounded ${status ? 'active': ''}"
onclick="toggle(status)"
>shuffle ${status} </span>
</button>
</div>
`;
}
$render(Shuffle);
If you have rendered Shuffle
, you need to remove $render(Shuffle);
at the end of the code snippets above.
$render
is a built-in utility to render and re-render JSX without a virtual DOM.
Note: passing a function with template literals adds the function to the DOM. For the function to work, it must end with a simi-colon(;)
and not contain any comments.
This issue can be avoided by configuring your code editor to insert ;
at the end of every line of code or by using utilities via the global utility accessor $utils()
. Learn more (opens in a new tab).
$trigger
is another built-in utility $render provides. Learn more (opens in a new tab).
Auto-insert semicolon(;) in VSCode
To configure VSCode to insert ;
at the end of every line of code, press Ctrl+,
or Command+,
to go to settings in VScode. Search "JavaScript semicolon" and under JavaScript>format:semicolon
, choose insert
.