Quick Tip: Dynamic Stencil Component Names With JSX
Stencil is a neat library for front-end development, but using JSX in your Stencil project can help make your code less verbose and easier to write.
Join the DZone community and get the full member experience.
Join For Free
Components composition is the main way to work with Stencil. There are occasions that we would like to decide dynamically which component to render as child component in some parent component. This can happen if you get the name of the component to render from the outside or need to decide the component according to some state. What can we do then?
One way to solve this is to put switch/case or if statements inside the component render function and get over with it. This solution is valid and will work but one of the main features of Stencil is the usage of JSX. So, how can we use JSX in our favor?
Let's take a look at the following example:
render() {
if (this.isInline) {
return (
<span>
<slot />
</span>
);
} else {
return (
<div>
<slot />
</div>
);
}
}
In the above example, isInline
is a Prop that is received from the Stencil component user. We can change this code to much more elegant code with our JSX knowledge:
render() {
const Tag = this.isInline ? 'span' : 'div';
return (
<Tag>
<slot />
</Tag>
);
}
Both of the solutions are valid but the second one is shorter and much more readable than the first, in my opinion.
Let me know what do you think about this option.
Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments