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
Susan SarandonOriginal
2024-11-01 17:09:02283browse

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

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>

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>

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!

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