Conditionally rendering JSX in React functions

·

1 min read

You might have occasion to render your JSX in React only in certain conditions. Like maybe if no props were passed to the function, rather than give an error, you just want nothing on the page instead.

The obvious thing to do would be this:

const App = () => {
  if (true) {
    return (
     <>
       <h1>This is a heading</h1>
       <p>This is a paragraph</p>
     </>
    )
  }
}

Makes sense, right? And as long the condition is true, then everything will be fine. But as soon as it's false React will complain that your function doesn't have a return statement. And all React functions should return something.

So instead you can do this:

const App = () => {
  return (
    <>
      {if(true) {
        <h1>This is a heading</h1>
        <p>This is a paragraph</p>
      }}
   </>
  )
}

And this will render the h1 and p tags only if the condition is true. If it's false all that's in the return statement are the empty tags. Which won't put anything on the page.

When adding JavaScript to JSX you have to put it in curly brackets, otherwise React gets confused. Hence the extra curly brackets around the condition (and general plethora of brackets all around the place).