JSX Basics

What is JSX?

JSX lets you write HTML-like markup in JavaScript. It is converted to React.createElement() calls by a compiler (Babel, SWC, esbuild).

const el = <h1 className="title">Hi</h1>;
// becomes
const el = React.createElement('h1', { className: 'title' }, 'Hi');

JSX Rules

  • Return one parent element (or a fragment <>...</>).
  • Close every tag: <img />, <br />.
  • Use className instead of class, htmlFor instead of for.
  • Attributes are camelCase: onClick, tabIndex.
  • Put JavaScript expressions in { }.
  • style takes an object: style={{ color: "red" }}.

Expressions in JSX

Example

Anything inside curly braces is evaluated as JavaScript.

export default function App() {
  const user = { name: 'Asha', age: 24 };
  const skills = ['HTML', 'CSS', 'React'];
  return (
    <>
      <h2 style={{ color: 'teal' }}>Hello {user.name.toUpperCase()}</h2>
      <p>Next year you will be {user.age + 1}.</p>
      <p>Skills: {skills.join(', ')}</p>
    </>
  );
}

Result