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) { // ... }
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> ); }
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 */} </> );
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!