Home >Web Front-end >JS Tutorial >How Do I Resolve \'Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag\' in React.js?

How Do I Resolve \'Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag\' in React.js?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 08:08:27480browse

How Do I Resolve

Parse Error: Resolving "Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag"

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!

Statement:
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