Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally add closing and starting JSX tags

I have never been able to figure out how to conditionally close off an existing JSX tag and start a new one without getting syntax errors in Visual Studio. How is this done? In the example below, I want to split an existing table into two tables. I don't get any syntax errors if I remove the conditional code.

<table>
    <thead>
        ...
    </thead>

    {true ?
     </table> /* Close first table (Syntax error on this line because of no starting tag) */
     <table>  /* Create a new table by splitting the existing table */
    : null}

    <tbody>
        ...
    </tbody>
</table>
like image 536
Lambert Avatar asked Sep 29 '16 15:09

Lambert


People also ask

What is JSX closing tag?

Any JSX element can be written with a self-closing tag, and every element must be closed. The line-break tag, for example, must always be written as <br /> in order to be valid JSX that can be transpiled. A <div> , on the other hand, can be written as <div /> or <div></div> .

Can you use if statements in JSX?

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.


1 Answers

You should not close a HTML tag inside the curly braces {}, unless it is created inside the curly braces.

Examples:

<div>
{</div>} //wrong

<div>
  {1 + 5}
</div> //correct

<div>
  {2+3 === 5 ? <div>hello</div> : <div>world</div>}
</div> //correct

<div>
  {2+3 === 5 ? <div>{6 + 7}</div> : <div>{5 + 5}</div>}
</div> //correct

Adding to that, {} can contain only a single node of HTML tag. If you have multiple nodes of HTML inside {}, React will throw an error.

Examples

<div>
 {
  <span>{1+2}</span>
  <span>{1+2}</span>
 }
</div> //will throw an error

<div>
 {
  <span>
   <span>{1+2}</span>
   <span>{1+2}</span>
  </span> 
 } 
</div> //correct

Hope it help!!

[Update]

For your case

{
 true //if true, this table will be rendered, else, null will be returned
  ? <table>
  <thead>
    ...
  </thead>
 </table>
 : null
}
<table> //this table will render all the time
 <tbody>
     ...
 </tbody>
</table>
like image 54
Pranesh Ravi Avatar answered Oct 04 '22 14:10

Pranesh Ravi