Home > Web Front-end > JS Tutorial > Why Do Adjacent JSX Elements Need Enclosing Tags in React.js?

Why Do Adjacent JSX Elements Need Enclosing Tags in React.js?

Susan Sarandon
Release: 2024-11-01 17:09:02
Original
274 people have browsed it

Why Do Adjacent JSX Elements Need Enclosing Tags in React.js?

Adjacent JSX Elements Require Enclosing Tag

When creating React.js components, it's essential to ensure that adjacent JSX elements are wrapped within an enclosing tag to avoid parse errors.

In the provided code snippet, the error:

Uncaught Error: Parse Error: Line 38: Adjacent JSX elements must be wrapped in an enclosing tag
Copy after login

indicates that the if statement's conditional rendering is causing the div elements to be rendered without an enclosing container. To resolve this issue, it's necessary to wrap these elements within a suitable tag, such as a div:

<code class="jsx">if (this.state.submitted === false) {
  return (
    <div>
      <input
        type="email"
        className="input_field"
        onChange={this._updateInputValue}
        ref="email"
        value={this.state.email}
      />
      <ReactCSSTransitionGroup
        transitionName="example"
        transitionAppear={true}
      >
        <div className="button-row">
          <a href="#" className="button" onClick={this.saveAndContinue}>
            Request Invite
          </a>
        </div>
      </ReactCSSTransitionGroup>
    </div>
  );
}</code>
Copy after login

Alternately, you can use the Fragments API to create an enclosing context without adding unnecessary elements to the DOM:

<code class="jsx">if (this.state.submitted === false) {
  return (
    <React.Fragment>
      <input
        type="email"
        className="input_field"
        onChange={this._updateInputValue}
        ref="email"
        value={this.state.email}
      />
      <ReactCSSTransitionGroup
        transitionName="example"
        transitionAppear={true}
      >
        <div className="button-row">
          <a href="#" className="button" onClick={this.saveAndContinue}>
            Request Invite
          </a>
        </div>
      </ReactCSSTransitionGroup>
    </React.Fragment>
  );
}</code>
Copy after login

The above is the detailed content of Why Do Adjacent JSX Elements Need Enclosing Tags in React.js?. 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