Fixing “Invalid JSX Error Due to Missing Closing Tag”
Common Causes
This error occurs when JSX elements aren’t properly closed, which can happen in several ways:
- Self-closing tags not properly formatted (
<div>
instead of<div />
) - Nested components missing closing tags
- HTML void elements incorrectly closed (like
<img>
vs<img />
) - Complex components with multiple children where one tag is left open
How to Identify the Problem
Error Message Examples
Parsing error: Unterminated JSX contents
Error: Expected corresponding JSX closing tag for <Component>
SyntaxError: Unexpected token, expected "..."
Common Problem Areas
- Multi-line JSX without proper closing
- Conditional rendering blocks
- Lists of components
- Components with many props spread across lines
Solutions
1. Basic Tag Closing
Incorrect:
<div> // ← Missing closing tag
<p>Content</p>
Correct:
<div>
<p>Content</p>
</div> // ← Properly closed
2. Self-Closing Elements
Incorrect:
<img src="image.jpg"> // ← Should be self-closed
<br> // ← Should be self-closed
Correct:
<img src="image.jpg" /> // Proper self-closing
<br /> // Proper self-closing
3. Component Nesting
Incorrect:
function Parent() {
return (
<div>
<Child> // ← Missing closing tag
Content
</div>
);
}
Correct:
function Parent() {
return (
<div>
<Child> // Properly nested
Content
</Child>
</div>
);
}
4. Fragments
Incorrect:
function Component() {
return (
<> // ← Fragment not closed
<p>Item 1</p>
<p>Item 2</p>
);
}
Correct:
function Component() {
return (
<> // Proper fragment syntax
<p>Item 1</p>
<p>Item 2</p>
</>
);
}
Debugging Tips
- Use syntax highlighting in your editor to spot unclosed tags
- Check indentation – misaligned tags often indicate problems
- Temporarily simplify complex JSX to isolate the issue
- Use ESLint with JSX rules to catch these errors early
ESLint Configuration
Add these rules to your .eslintrc
to prevent issues:
{
"rules": {
"react/jsx-closing-tag-location": "error",
"react/jsx-tag-spacing": "error",
"react/self-closing-comp": "error"
}
}
Common Pitfalls
- Conditional rendering where branches have different structures
- Mapping over arrays where some items return undefined
- Ternary operators in JSX with unbalanced tags
- Multi-line attributes making tags hard to visually pair