Components and JSX · Lesson 2 of 21
JSX rules
One parent element, className, {} for JavaScript, and style as an object.
JSX looks like HTML but is JavaScript. A tool called Babel turns <h1>Hi</h1> into React.createElement("h1", null, "Hi"). That's why a few rules differ from HTML:
| HTML | JSX | Why |
|---|---|---|
class="card" | className="card" |
|
for="email" | htmlFor="email" |
|
<br> | <br /> | every tag must close |
onclick="…" | onClick={fn} | camelCase, and you pass a function |
style="color: red" | style={{ color: 'red' }} | an object, not text |
function App() {
const student = { name: "Nour", xp: 410 }
const level = Math.floor(student.xp / 100)
return (
<>
<h2 className="title">{student.name.toUpperCase()}</h2>
<p style={{ color: "teal", fontWeight: "bold" }}>
Level {level}, {student.xp >= 400 ? "top student" : "keep going"}
</p>
<label htmlFor="note">Note</label>
<input id="note" placeholder="Write something" />
</>
)
}- Anything between
{ }is a JavaScript expression: a variable, a calculation, a function call, a ternary. Notiforfor(those are statements). - A component must return one parent element. If you don't want an extra
div, use a Fragment<>…</>. styletakes an object with camelCase keys:fontWeight, notfont-weight.
Spot the bug
This code won't work. Which line has the problem?
Complete the code
Complete it so the class applies and the text is red.
function App() { return <p ="warning" style={{ color: }}>Careful!</p> }
Exercise
You have const price = 450 and const discount = 0.2. Show Final price: 360 EGP in a <p>, computing the number inside { }.
The page should show: Final price: 360 EGP
function App() {
const price = 450
const discount = 0.2
return <p>Final price: EGP</p>
}Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.