B4Coder
0%
LessonAbout 6 min

Chapter 1 · Lesson 3 of 5

03. Components of your own

Make your own components and use them like HTML tags: write one once, show it as many times as you like.

Any function that returns JSX, with a name starting with a capital letter, is a component. Use it like a tag: <Welcome />. Write it once, use it many times.

JSX
function Rule() {  return <p className="rule">Be kind. Be on time.</p>;}
export default function App() {  return (    <div>      <h1>Class rules</h1>      <Rule />      <Rule />    </div>  );}

The capital letter matters: <Rule /> is your component, but <rule /> would be treated as an unknown HTML tag. Components can use other components, and that's how big apps are built: App uses Header, Header uses Logo, and so on.

Your turn

1Steps

  1. 1Make a component called Star that returns <span className="star">★</span>.
  2. 2In App, show a heading My rating, and then a <div className="stars"> with your Star used 4 times.

Write your component in App.jsx, as export default function App(); the preview shows it as you type.

Starting code

The editor starts empty. Copy this into it to begin, or write your own from scratch.

JSX
export default function App() {  return (    <div>      <h1>My rating</h1>      <div className="stars">★★★★</div>    </div>  );}

2Expected output

Your page should have

  • The heading says My rating
  • There are exactly 4 stars
  • Each star shows ★
  • App.jsx has a component called Star
  • App uses <Star />

Submit answer checks each of these.

3Hints

Stuck? Open one hint at a time: each gives a bit more help.

Hint 1

Write function Star() { … } above App, returning one span.

Hint 2

function Star() { return <span className="star">★</span>; }

Hint 3

In App: <div className="stars"><Star /><Star /><Star /><Star /></div>

Console · what App.jsx logs

Nothing logged yet. console.log(…) in App.jsx shows here.