Home >Web Front-end >JS Tutorial >Why am I getting a \'Parse Error: Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag\' error in React?
When rendering React components, it's essential to adhere to the rule that adjacent JSX elements must be enclosed in a parent tag. This error occurs when elements exist side-by-side without being wrapped by a common parent.
The provided code contains an if statement that conditionally renders two div elements based on the value of the this.state.submitted variable. However, these elements are adjacent and not enclosed in any parent tag.
To resolve this error, wrap the conditionally rendered elements within an enclosing tag. This will ensure that the JSX structure is valid. For example, you could modify the code to the following:
<code class="javascript">render: function() { var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:'; var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {}; return ( <div> {this.state.submitted == false && ( <> <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>
In this modified code, we have enclosed the conditionally rendered elements within an enclosing
As an alternative to using an additional div tag, you can use the Fragments API. This allows you to group elements without adding an extra node to the DOM. The following code showcases how you can use fragments:
<code class="javascript">render: function() { var text = this.state.submitted ? 'Thank you! Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:'; var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {}; return ( <div> {this.state.submitted == false && ( <> <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>
In this code, we have used the The above is the detailed content of Why am I getting a \'Parse Error: Adjacent JSX Elements Must Be Wrapped in an Enclosing Tag\' error in React?. For more information, please follow other related articles on the PHP Chinese website!