~/
hackweb.dev
JSX Syntax
Quiz
⌘K
...
~/
/tutorials
/react/react-jsx/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/react/2react-jsx
Write
Preview
Diff
# JSX Syntax JSX is a syntax extension for JavaScript that looks like HTML. React uses it to describe what the UI should look like. ## Embedding Expressions Wrap any JavaScript expression in curly braces `{}`: ```jsx const name = "Alice"; const element = <h1>Hello, {name}!</h1>; ``` You can use any expression — variables, function calls, ternaries, math. ## Self-Closing Tags Every tag must be closed. HTML-style self-closing works: ```jsx const img = <img src="photo.jpg" alt="Photo" />; const input = <input type="text" />; ``` Forgetting the `/` is a common syntax error. ## Fragments Return multiple elements without an extra wrapper: ```jsx function List() { return ( <> <li>One</li> <li>Two</li> </> ); } ``` `<>` is shorthand for `<React.Fragment>`. No extra DOM nodes are created. ## JSX is Not HTML JSX uses camelCase for attributes: ```jsx // HTML JSX class="box" → className="box" for="email" → htmlFor="email" onclick={handler} → onClick={handler} tabindex="0" → tabIndex="0" ``` Style values are objects, not strings: ```jsx <div style={{ color: "red", fontSize: "16px" }}>Red text</div> ``` ## Returning JSX A component must return a single root element: ```jsx function Card() { return ( <div> <h2>Title</h2> <p>Body</p> </div> ); } ``` Use a fragment if you don't need a wrapper div. ## Best Practices 1. **Use fragments** — Avoid unnecessary divs in the DOM 2. **Keep JSX readable** — Break into multiple lines for complex elements 3. **Use className and htmlFor** — Not `class` and `for` 4. **Self-close empty tags** — `<img />`, `<input />`, `<br />` ## Common Mistakes 1. **Forgetting return parentheses** — Multi-line JSX needs `()` after `return` 2. **Using `class` instead of `className`** — JSX uses camelCase 3. **Returning multiple root elements** — Wrap in a fragment or div 4. **Using quotes for dynamic values** — Use `{}` for JavaScript expressions
No changes yet
Reset to original
Submit suggestion
cancel