React · Lesson 5 of 120
JSX Rules
One parent, close every tag.
JSX is a little stricter than HTML. There are three rules to remember. Return one parent element. Close every tag. And write attributes in camel case.
- One parent
- Close every tag
- camelCase
Following the rules
A fragment, the empty tags, wraps everything in one parent, without adding an extra element. The image tag closes itself with a slash. And the class attribute is written class name. Run it.
App.jsxjsx
export default function App() {
return (
<>
<h1>Trail 500</h1>
<img src="bike.svg" alt="Trail 500 bike" width="200" />
<p className="box">A tough mountain bike for muddy trails.</p>
</>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses bike.svg
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="90" viewBox="0 0 200 90"><rect width="200" height="90" rx="12" fill="#61dafb"/><g fill="none" stroke="#111" stroke-width="5"><circle cx="55" cy="58" r="20"/><circle cx="145" cy="58" r="20"/><path d="M55 58 L85 28 L120 28 L145 58 M85 28 L100 58 L120 28"/></g></svg>HTML vs JSX
Class becomes class name, because class is a JavaScript keyword. For becomes HTML for. Event names are camel case, like on click. And every tag must close, even images and line breaks.
| HTML | JSX |
|---|---|
| class | className |
| for | htmlFor |
| onclick | onClick |
| <br> | <br /> |
Summary
Return one parent, close every tag, and use camel case attributes. Next, JavaScript inside JSX.
Key takeaways- <>...</>
- <img />
- className
Next up: JavaScript in JSX — curly braces