Props and lists
Reuse a component with different values, and show a list from an array.
Your React code is compiled and run by React itself, inside your browser tab. Nothing to install.
Using your own component
A component can be used inside another, written as a tag. Its name must start with a capital letter, so React can tell it from an HTML tag.
This lets you build a page from small named parts.
function Footer() {
return <p>Open from 7 am to 2 pm</p>;
}
export default function App() {
return (
<div>
<h1>Asha's Bakery</h1>
<Footer />
</div>
);
}Props
Props are how a component is given values. They are written like attributes on the tag.
The component receives them as one object. Writing { name } in the function's brackets picks the name prop out of it.
The same component can now show different things each time it is used.
function Greeting({ name }) {
return <p>Hello, {name}</p>;
}
export default function App() {
return (
<div>
<Greeting name="Asha" />
<Greeting name="Bilal" />
</div>
);
}Your turn: a component with a prop
Write a component above App and use it twice.
Practice task
Above App, write a component called Price that takes a prop called amount and shows a paragraph reading Rs followed by the amount. Use it twice in App, with 40 and with 75.
Your answer is run and checked in the lesson. Create a free account to try it.
Lists from arrays
To show a list, turn each item of an array into an element with map.
Each element made this way needs a key: a value that is different for every item, so React can tell them apart when the list changes.
export default function App() {
const breads = ["Sourdough", "Rye", "Focaccia"];
return (
<ul>
{breads.map((bread) => (
<li key={bread}>{bread}</li>
))}
</ul>
);
}Your turn: a list
Use map, not three typed-out items.
Practice task
Create an array called drinks holding Tea, Coffee and Lassi. Show it as a bulleted list with one item for each drink.
Your answer is run and checked in the lesson. Create a free account to try it.