Home > Article > Web Front-end > How Do I Resolve \"Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag\" in React.js?
When attempting to conditionally render components in a React.js application, developers may encounter the error "Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag." This occurs when multiple JSX elements are placed directly adjacent to each other without being contained within a parent component.
The error can be fixed by ensuring that all JSX elements are enclosed within a single parent component, as seen below:
// Incorrect: Adjacent JSX elements will result in a parse error return ( <Comp1 /> <Comp2 /> );
// Correct: Enclose elements within a parent component return ( <div> <Comp1 /> <Comp2 /> </div> );
Alternatively, the React.Fragment API can be utilized to create a virtual parent component without adding extra DOM nodes:
// Fragments allow for grouping JSX elements without adding nodes to DOM return ( <React.Fragment> <Comp1 /> <Comp2 /> </React.Fragment> );
By enclosing adjacent JSX elements within an appropriate parent component, developers can resolve the "Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag" error and ensure that their React applications render as expected.
The above is the detailed content of How Do I Resolve \"Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag\" in React.js?. For more information, please follow other related articles on the PHP Chinese website!