1

I'm having error with conditional rendering in Nextjs. If I have 1 component it works. With multiple components (block of code), it doesn't work

-> Its work:

const MyComponent = () => {
  return (
    <h1>Hello word</h1>

    { (isTrue) ? (
        <Text>Component 1</Text>
      ) : 'No component'
    }
  )
}

-> DON'T work :(

const MyComponent = () => {
  return (
    <h1>Hello word</h1>

    { (isTrue) ? (
        <Text>Component 1</Text>
        <Text>Component 2</Text>
      ) : 'No component'
    }
  )
}

2 Answers2

2

It's not possible to render multiple elements / components at a time in React. You always have to wrap them in a single element or using a react fragment. For example, in your case should be:

const MyComponent = () => {
  return (
   <>
    <h1>Hello word</h1>

    { (isTrue) ? (
        <>
           <Text>Component 1</Text>
           <Text>Component 2</Text>
        </>
      ) : 'No component'
    }
   </>
  )
}

https://bobbyhadz.com/blog/react-conditional-multiple-elements#conditionally-render-multiple-elements-in-react

https://reactjs.org/docs/fragments.html

Eric Aig
  • 972
  • 1
  • 13
  • 18
1


Yeah it might not work,
but you could try this by the use of fragments.

const MyComponent = () => {
return (
  <h1>Hello word</h1>

  { (isTrue) ? (
      <>
        <Text>Component 1</Text>
        <Text>Component 2</Text>
      </>
      ) : 'No component'
    }
  )
}
AVDiv
  • 11
  • 7