Invalid JSX error due to missing closing tag

Loading

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:

  1. Self-closing tags not properly formatted (<div> instead of <div />)
  2. Nested components missing closing tags
  3. HTML void elements incorrectly closed (like <img> vs <img />)
  4. 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

  1. Multi-line JSX without proper closing
  2. Conditional rendering blocks
  3. Lists of components
  4. 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

  1. Use syntax highlighting in your editor to spot unclosed tags
  2. Check indentation – misaligned tags often indicate problems
  3. Temporarily simplify complex JSX to isolate the issue
  4. 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

  1. Conditional rendering where branches have different structures
  2. Mapping over arrays where some items return undefined
  3. Ternary operators in JSX with unbalanced tags
  4. Multi-line attributes making tags hard to visually pair

Leave a Reply

Your email address will not be published. Required fields are marked *