I am using StencilJS to create some web components. I created a utility component since I saw myself reusing some logic again and again:
export type ConditionalRenderProps = {
condition: boolean;
};
const ConditionalRender = ({ condition, children }: React.PropsWithChildren<ConditionalRenderProps>) => {
return condition && children ? children : null;
};
However, when I use it as such in a Stencil component, the children props is undefined:
Component({
tag: 'foo',
styleUrl: 'foo.css'
shadow: true,
})
export class Foo {
render() {
return (
<Host>
<ConditionalRender condition={true}>
<span>foo</span>
</ConditionalRender>
</Host>
);
}
}
Is there a catch? Why is children
undefined?
I think you're mixing React and Stencil, which won't work like that.
You can instead use a Stencil functional component, the main difference being that the children are passed in a second argument:
import { FunctionalComponent } from '@stencil/core';
export type ConditionalRenderProps = {
condition: boolean;
};
export const ConditionalRender: FunctionalComponent<ConditionalRenderProps> = ({ condition }, children) => {
return condition && children ? children : [];
};
Update
Previously, the code would return null
if the condition wasn't true
. Since the return type of Functional Components is VNode | VNode[]
I changed it to an empty array instead.