SyntaxStudy
Sign Up
React JSX Fragments, Comments, and Whitespace
React Beginner 1 min read

JSX Fragments, Comments, and Whitespace

React Fragments let you group multiple sibling elements without adding an extra DOM node. This is important when a component must return more than one element but the extra wrapper div would break your CSS layout (for example inside a flex or grid container). You can use the long form `` or the short syntax `<>...`. Only the long form accepts a `key` prop, which is necessary when rendering fragments inside a list. JSX comments look like JavaScript block comments wrapped in expression braces: `{/* comment here */}`. Regular HTML comments (``) are not valid in JSX. Whitespace handling in JSX differs slightly from HTML: consecutive whitespace between JSX elements on separate lines is collapsed, so if you need a space between two inline elements you must include it explicitly inside a string or use the non-breaking space entity. Knowing these details prevents subtle bugs and linting errors. A component that returns a bare fragment instead of a wrapper div keeps the DOM clean and makes it easier to compose layouts. The ability to comment out JSX during debugging without breaking the surrounding markup is also a practical day-to-day tool.
Example
import React from 'react';

// Short fragment syntax (most common)
function TagList({ tags }) {
  return (
    <>
      <h4>Tags</h4>
      <ul>
        {tags.map(tag => (
          <li key={tag}>{tag}</li>
        ))}
      </ul>
    </>
  );
}

// Long form required when key is needed (e.g. inside a list)
function DefinitionList({ items }) {
  return (
    <dl>
      {items.map(item => (
        <React.Fragment key={item.term}>
          <dt>{item.term}</dt>
          <dd>{item.definition}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}

// JSX comments — wrap in { }
function Annotated() {
  return (
    <div>
      {/* This is a JSX comment — invisible in output */}
      <p>Visible text</p>
      {/* <p>Commented-out element</p> */}

      {/* Explicit space between inline elements */}
      <strong>Bold</strong>{' '}<em>Italic</em>
    </div>
  );
}

export default TagList;