Components and JSX
You'll learn to read and write a React component, a function that returns JSX.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want a page with ten cricket score cards. Writing the same HTML ten times is slow, and a change means ten edits. Instead you write the card once, give it a name, and use it as many times as you like. That named, reusable piece of screen is called a component.
In React, a component is a function that returns what the screen should show. The returned part looks like HTML, but it lives inside JavaScript. It is called JSX.
function ScoreCard() {const runs = 245;return <p>Bangladesh: {runs} runs</p>;}
The { } inside JSX is a window back into JavaScript. {runs} shows the value of runs, so the screen
says "Bangladesh: 245 runs". You can put any value there, like {runs + 4}.
You use a component like a tag: <ScoreCard />. React calls the function and puts what it returns on
the screen. This is called rendering.
A few JSX rules you will meet every day:
- Return one outer element. Wrap siblings in a
<div>or an empty<>...</>. - Write
className, notclass, becauseclassis a JavaScript word. - Close every tag, even
<img />and<br />.
People often name a component with a small letter. <scoreCard /> is treated as an unknown HTML
tag, and nothing of yours shows. Component names always start with a capital letter.
Real projects are started with Vite: run npm create vite@latest and pick React. Old tutorials use
create-react-app; it is no longer recommended, so skip that part of any video.
When you read a component, look at what it returns, then find every { } and ask: what value goes here?
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1function Greeting() {2 const name = "Nusrat";3 return <h1>Hello, {name}!</h1>;4}56export default function App() {7 return (8 <div>9 <Greeting />10 <Greeting />11 </div>12 );13}
Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3With
const runs = 245;, what does<p>Runs: {runs + 5}</p>show? - 2 / 3Why must a component name start with a capital letter?
- 3 / 3How do you give a JSX element the CSS class
card?
Explain it back
How confident are you with Components and JSX?
Done
{ }.