JSX (JavaScript XML) lets you write HTML-like syntax inside JavaScript. React transforms JSX into React.createElement() calls.

Basic JSX

  const element = <h1>Hello, World!</h1>;
  

JSX Rules

1. Single Root Element

  // Invalid
return (
    <h1>Title</h1>
    <p>Paragraph</p>
);

// Valid — wrap in fragment or div
return (
    <>
        <h1>Title</h1>
        <p>Paragraph</p>
    </>
);
  

2. Close All Tags

  <img src="photo.jpg" alt="Photo" />
<input type="text" />
<br />
  

3. camelCase Attributes

  <div className="container" tabIndex={0} onClick={handleClick}>
    <label htmlFor="email">Email</label>
</div>
  
HTML JSX
class className
for htmlFor
onclick onClick
tabindex tabIndex

Embedding Expressions

Use curly braces {} for JavaScript expressions:

  const name = 'Alice';
const count = 5;

return (
    <div>
        <h1>Hello, {name}!</h1>
        <p>{count * 2} items</p>
        <p>{count > 0 ? 'Has items' : 'Empty'}</p>
    </div>
);
  

Conditional Rendering

  // Ternary
{isLoggedIn ? <Dashboard /> : <Login />}

// Logical AND
{error && <p className="error">{error}</p>}

// If/else with variable
let content;
if (loading) {
    content = <Spinner />;
} else {
    content = <DataList data={data} />;
}
return <div>{content}</div>;
  

Rendering Lists

  const fruits = ['Apple', 'Banana', 'Cherry'];

return (
    <ul>
        {fruits.map((fruit, index) => (
            <li key={index}>{fruit}</li>
        ))}
    </ul>
);
  

Always provide a unique key prop when rendering lists.

Inline Styles

  const styles = {
    color: 'blue',
    fontSize: '18px',
    backgroundColor: '#f0f0f0'
};

return <p style={styles}>Styled text</p>;
  

JSX Compiles To

  <h1 className="title">Hello</h1>

// Becomes:
React.createElement('h1', { className: 'title' }, 'Hello');
  

Comments in JSX

  return (
    <div>
        {/* This is a JSX comment */}
        <h1>Title</h1>
    </div>
);
  

JSX is the primary way to describe UI in React — it combines the power of JavaScript with familiar HTML syntax.