Props: Components with Inputs
Write a component once and reuse it with different values.
1function Greeting({ name }) {
2 return <p>Hello, {name}!</p>;
3}
4
5function App() {
6 return (
7 <div>
8 <Greeting name="Ada" />
9 <Greeting name="Grace" />
10 </div>
11 );
12}
13export default App;
$ npm run dev
VITE v5.4 ready in 312 ms
Local: http://localhost:5173/
(your app is live: look at the browser window above!)
Every line, explained
function Greeting({ name }) {- A second component, and this one takes an input! Props are values passed INTO a component, like function parameters. The curly braces in { name } unpack the prop called name (a JavaScript trick called destructuring: it pulls a value out by its name).
return <p>Hello, {name}!</p>;- The component uses its prop like any variable. Same component + different props = different output.
}- This } closes the component function.
function App() {- App can now USE Greeting, because components are built from other components. That is how big apps stay manageable: small pieces, combined.
return (- When JSX spans several lines, it goes inside round brackets after return. The brackets keep the JSX attached to the return: without them, JavaScript would think the return finished at the end of that line and hand back nothing.
<div>- A component must return ONE outer tag. Putting two siblings side by side at the top level is an error, so a wrapping <div> holds them together.
<Greeting name="Ada" />- Your own component, used as a tag! A capital letter tells React "this is a component, not a plain HTML tag". name="Ada" passes the prop in, and the /> is a self-closing tag: open and shut in one go.
<Greeting name="Grace" />- Reuse: the same Greeting with a different prop. Two lines, two different greetings on screen.
</div>- Closing tag for the wrapping div.
);- The ); closes the return's round bracket.
}- This } closes the component function.
export default App;- export default App hands your component to the rest of the app. A locked line in every lesson: the app's starter file (main.jsx) imports App and mounts it on the page.