4

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?

Marek Krzeminski
  • 1,308
  • 3
  • 15
  • 40

1 Answers1

5

You can achieve that using the following code:

render() {
   const Tag = this._isInline ? 'span' : 'div';
   return (
     <Tag>
       <slot />
     </Tag>
   );
}
Gil Fink
  • 747
  • 9
  • 10
  • thank you, I didn't think to try using the variable without the curly brackets around it. As you may have guessed, I'm new to JSX. Now if I could figure out why my TSX file is showing a warning about Tag not being used. [ts] 'Tag' is declared but its value is never read. – Marek Krzeminski Sep 14 '18 at 13:02
  • Note it is important that Tag is declared with a capital letter 'T'. If you instead declare "const tag = ..." with a lower case 't', then you will get a warning and the item will not render. – Safa Alai Aug 09 '19 at 17:14