React JSX expressions must have one parent element.

created at 01-03-2022 views: 3

problem

When I tried duplicate the components in return, i got this error propt.

code example:

 function WelcomeDialog(){
      return (
        <FancyBorder color='blue'>
            // content1 
        </FancyBorder>

        <FancyBorder color='Red'>
            // content2
        </FancyBorder>
      );
    }

    ReactDOM.render(
      <WelcomeDialog />,
      document.getElementById('root')
    )

and in the browser console, I got the error

Uncaught SyntaxError: Inline Babel script: Adjacent JSX elements must be wrapped in an enclosing tag (24:8)

solution

wrap the components in <React.Fragment> tag:

 function WelcomeDialog(){
      return (
      <React.Fragment>// here
        <FancyBorder color='blue'>
            // content1 
        </FancyBorder>

        <FancyBorder color='Red'>
            // content2
        </FancyBorder>
      </React.Fragment> // and here
      )
    }

and it will be OK.

Please log in to leave a comment.