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'
}
)
}
CodePudding user response:
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://reactjs.org/docs/fragments.html
CodePudding user response:
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'
}
)
}