Search code examples
javascriptjsxrenderstenciljstsx

stenciljs conditional render return in tsx


my stenciljs render function is currently written in typescript this way:

render() {
  if( this._isInline ) {
    return (
      <span>
        <slot />
      </span>
    );
  } else {
    return (
      <div>
        <slot />
      </div>
    );
  }
}

but I prefer if I could write it something like this:

render() {
  const tag = this._isInline ? 'span' : 'div';
  return (
    <{tag}>
      <slot />
    </{tag}>
  );
}

but this gives me a bunch of error messages.

Is there a way to write the jsx code so that I have conditional open and closing tags?


Solution

  • You can achieve that using the following code:

    render() {
       const Tag = this._isInline ? 'span' : 'div';
       return (
         <Tag>
           <slot />
         </Tag>
       );
    }