DEV Community

Nic
Nic

Posted on

Conditionally rendering JSX in React functions

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>
     </>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

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>
      }}
   </>
  )
}
Enter fullscreen mode Exit fullscreen mode

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).

Latest comments (1)

Collapse
 
mrchedda profile image
mr chedda

The preferred method to conditionally render a component is:

export default function App(){
    { conditionalStatement && ( 
         <RenderedComponent /> 
    )}
}
Enter fullscreen mode Exit fullscreen mode

OR

export default function App(){
    { conditionalStatement ? ( 
        <RenderedComponentOne /> 
    ):( 
        <RenderedComponentTwo />
    )}
}
Enter fullscreen mode Exit fullscreen mode