Note JSX is syntactic sugar for function calls. Every tag must be closed. Use className instead of class, htmlFor instead of for. Attribute names follow camelCase convention.
jsx syntaxjsx rulesjsx basicswrite jsx
Embedding Expressions
syntax
{expression}
// Any valid JavaScript expression inside curly braces
Note You can embed any JavaScript expression inside curly braces: variables, function calls, math, ternaries. Statements (if, for, while) cannot appear inside JSX directly -- use them before the return.
jsx expressionembed javascriptcurly bracesdynamic content in jsx
Note For more than two branches, extract the logic into a variable or helper function above the return statement rather than nesting ternaries. Readable code wins over clever one-liners.
function FormField({ label, ...inputProps }) {
return (
<div className="field">
<label>{label}</label>
<input {...inputProps} />
</div>
);
}
// Usage: all standard input attributes are forwarded
<FormField
label="Email"type="email"
placeholder="you@example.com"
required
/>
Note Spread is great for forwarding props. Be careful: it can pass unintended attributes to DOM elements. Destructure known props first, then spread the rest.
spread propsforward propspass all propsrest propsproxy component
// This JSX:const element = (
<div className="container">
<h1>Title</h1>
<p>Paragraph</p>
</div>
);
// Compiles to:const element = React.createElement(
"div",
{ className: "container" },
React.createElement("h1", null, "Title"),
React.createElement("p", null, "Paragraph")
);
Note You almost never need to call createElement directly. JSX is syntactically cleaner and the standard in the ecosystem. The JSX transform in modern setups does not require importing React at the top of every file.
jsx createElementjsx compilationwithout jsxhow jsx works
Note Style properties use camelCase (backgroundColor, not background-color). Values that need units must include them as strings ("8px"), except for unitless properties like opacity and zIndex which accept numbers.