Home > Web Front-end > JS Tutorial > Why do I get \'Adjacent JSX elements must be wrapped in an enclosing tag?\'

Why do I get \'Adjacent JSX elements must be wrapped in an enclosing tag?\'

Patricia Arquette
Release: 2024-11-02 18:07:29
Original
349 people have browsed it

Why do I get

Adjacent JSX Elements Must be Enclosed

When attempting to conditionally render components based on a state variable, it is essential to adhere to the rule that adjacent JSX elements must be wrapped within an enclosing tag. This requirement ensures the validity of the React component tree.

The issue arises when you use an if statement to conditionally render elements without enclosing them properly. For instance, in your code:

if(this.state.submitted==false) {
  // ...
}
Copy after login

This results in the parse error "Adjacent JSX elements must be wrapped in an enclosing tag." To resolve this, you must wrap the conditional elements within a suitable parent tag, such as a

:

if(this.state.submitted==false) {
  return (
    <div>
      {/* Conditional content here */}
    </div>
  );
}
Copy after login

Alternatively, if you wish to display fragments without an additional layer of wrapping, you can leverage the Fragments API introduced in React 16.2:

return (
  <>
    {/* Conditional content here */}
  </>
);
Copy after login

This syntax allows you to group JSX elements without introducing additional DOM nodes.

The above is the detailed content of Why do I get \'Adjacent JSX elements must be wrapped in an enclosing tag?\'. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template