3

Actually i'm trying to hide and show some html elements in react. I have a created a employee form in which we have multiple partitions for example personal information, contact information etc... I created next and previous buttons in form to show and hide other partitions in the form There is a partition in which we have education details to fill, so i chose to keep a plus and minus button to add education details using conditions.

But finally, my problem is like i have complex conditions on **render** function:

{someCondition && <div>
{anotherCondition && <div></div>}
</div>}

But, i'm getting: *Adjacent JSX elements must be wrapped in an enclosing tag error*. So, what i'm supposed to do? 
Manikanta B
  • 1,083
  • 2
  • 16
  • 30

3 Answers3

7

You have to wrap them in a div first. Also, your syntax looks a bit wrong (you missed a closing }).

{someCondition && (
  <div>
    {anotherCondition && <div></div>}
  </div>
)}
Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
2

From the code you gave, I believe you need an enclosing tag like this:

//div wraps everything else so the component can render.
<div>
{someCondition && <div>
{anotherCondition && <div></div>
</div>}
</div>
Dream_Cap
  • 2,292
  • 2
  • 18
  • 30
1

You must always return one single element enclosing the others.

As regarding conditional rendering, here are some other tips you can consider:

A. for simple conditions, ternary operator is clean enough:

return condition ? <p>abc</p> : <p>def</p>

B. create rendering functions for cleaner code or more complicated if-else

renderButton = () => {
  if (isLoading) { return false }
  if (something) {
    return <div></div>
  } else {
    return <div></div>
  }
}

render() {
  return (
    <div>
      { this.renderButton }
    </div>
  )
}

C. same as above, but without create new functions:

render() {
  return (
    <div>
    {
      (()=>{
        if (something) {
          return <div></div>
        } else {
          return <div></div>
        }
      })()
    }
    </div>
  )
}
Liren Yeo
  • 3,215
  • 2
  • 20
  • 41