React报错Unterminated JSX contents,程序看似正常却无法运行求助
Hey there! I’ve run into this exact Unterminated JSX contents error more times than I’d like to admit—super frustrating when your code looks fine at a glance. Let’s break down the most common culprits and how to fix them:
Unclosed JSX tags
This is the #1 cause. JSX requires every tag to be properly closed, either with a matching closing tag or a self-closing slash. For example:
❌ Wrong (missing closing tag):<div className="container"> <h1>Hello World </div>❌ Wrong (missing self-closing slash):
<img src="/logo.png" alt="Logo"✅ Correct:
<div className="container"> <h1>Hello World</h1> </div> <img src="/logo.png" alt="Logo" />Incomplete JavaScript expressions inside JSX
When embedding JS with{}, make sure your code is fully closed. A missing bracket, parenthesis, or arrow function body will trigger this error. For example:
❌ Wrong (missing closing bracket and JSX tag):<ul> {users.map(user => <li>{user.name} </ul>✅ Correct:
<ul> {users.map(user => <li>{user.name}</li>)} </ul>Broken multi-line JSX formatting
Sometimes auto-formatters or manual line breaks can split tags in ways that leave them incomplete. Double-check lines where you’ve split a tag across multiple lines:
❌ Wrong (missing closing button tag):<button className="primary-btn" onClick={handleSubmit} Submit✅ Correct:
<button className="primary-btn" onClick={handleSubmit} >Submit</button>Malformed JSX comments
JSX doesn’t support regular//comments inside its tags—you must use the{/* ... */}syntax, and make sure the comment is fully closed:
❌ Wrong (unclosed comment):<div> {/* This is a comment that never ends <p>Content here</p> </div>✅ Correct:
<div> {/* This is a properly closed comment */} <p>Content here</p> </div>Mismatched nested JSX hierarchy
If you’re nesting multiple components, it’s easy to overlook a closing tag deeper in the tree. For example:
❌ Wrong (missing closing<li>and<section>):<section> <h2>My List</h2> <ul> <li>First Item <li>Second Item </ul>✅ Correct:
<section> <h2>My List</h2> <ul> <li>First Item</li> <li>Second Item</li> </ul> </section>
A quick pro tip: Use ESLint with React rules enabled—it’ll usually highlight the exact line where the unclosed content starts, saving you tons of time scanning manually.
内容的提问来源于stack exchange,提问作者szelattila




