Quick Tip — Dynamic Stencil Component Names with JSX

Gil Fink
2 min readSep 14, 2018

--

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 to 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 previous example the isInline is a Prop that is received from the Stencil component user. We can change this code to a 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 then the first IMHO.

Let me know what do you think about this option.

--

--

Gil Fink
Gil Fink

Written by Gil Fink

Hardcore web developer, @sparXys CEO, Google Web Technologies GDE, Pro SPA Development co-author, husband, dad and a geek.