Poet and JSX differences
In this article, we will present a few examples that cover the biggest differences in the syntax between Poet ans JSX.
The examples follow the same structure: both present code that achieves the same result, first in JSX and then in Poet's Rhai-based syntax.
No need for <Fragment>
While the HTML code in Poet needs to be correct, there's no need for the
fn template(context, props, content) {
component {
Title
Paragraph
}
}
if-else statements
Instead of using ternary operators, you can use regular if-else statements because they are treated as expressions in Rhai.
For example, here we're checking if the "type" property exists in props and then I modify the class accordingly:
fn template(context, props, content) {
component {
{content}
}
}
And here, we're checking if the description property in the front matter is empty:
<meta
name="description"
content=
/>
switch statement
Rhai treats switches as expressions so they can be placed them directly inside shortcodes.
fn template(context, props, content) {
component {
{switch props.type {
"note" => component {
{content}
},
"banner" => component {
{props.children}
}
}}
}
}
class instead of className
In Poet, you use class
instead of className
to define CSS classes.
<div className="homepage">
<h1 className="homepage__title">
Keep AI on your own servers
</h1>
<a className="homepage__button" href="/docs">
Get Started
</a>
</div>
component {
Keep AI on your own servers
Get Started
}
error() global function
An example of an error function that raises an error with a custom message.
if !props.role {
error("Role required");
}
clsx() global function
Another example of a global function in Poet is the clsx() for conditionally composing classe: