DevNotes

DevNotes

@devnotes ·

React Part 3: Pass data with props

A component that always shows the same thing isn't much use. Props let you pass data into a component, so one ProductCard can show a thousand different products.

Passing props and reading them

You pass props the way you write HTML attributes:

JSX
<ProductCard name="Steel bottle" price={349} inStock={true} />

Strings go in quotes. Everything else goes in curly braces: numbers, booleans, arrays, objects and functions.

The component receives all its props as one object, and you'd usually unpack it straight away with destructuring, from JavaScript Part 7:

JSX
function ProductCard({ name, price, inStock }) {  return (    <div className="card">      <h3>{name}</h3>      <p>Rs {price}</p>      {!inStock && <p className="muted">Out of stock</p>}    </div>  );}

{!inStock && <p>...</p>} shows that paragraph only when inStock is false. React Part 6 covers this pattern properly.

Now one component serves every product:

JSX
<>  <ProductCard name="Steel bottle" price={349} inStock={true} />  <ProductCard name="Lunch box" price={499} inStock={false} /></>

Default values

JSX
function Avatar({ src, name, size = 40 }) {  return <img src={src} alt={name} width={size} height={size} />;}

If no size is passed, it's 40. It's the same default syntax you used for functions in JavaScript Part 5.

Props only flow down

Data moves one way: from a parent component down to its children. A child should never change the props it receives. Treat them as read-only. If a value needs to change over time, it belongs in state, which is the next part.

This one-way flow is what makes React apps predictable. To find out where a value comes from, you look up the tree, never sideways.

children: wrapping content

Whatever you put between a component's opening and closing tags arrives as a special prop called children:

JSX
function Card({ title, children }) {  return (    <section className="card">      <h2>{title}</h2>      {children}    </section>  );}
<Card title="About me">  <p>Second year student who likes building small tools.</p></Card>

This is how you build layout pieces, like a card, a pop-up or a page frame, that work with any content inside them.

Passing functions

Props can be functions too, and that's how a child tells its parent that something happened:

JSX
function LikeButton({ onLike }) {  return <button onClick={onLike}>Like</button>;}
<LikeButton onLike={() => console.log("Liked!")} />

The parent decides what liking does, and the button only reports the click. Once state comes in, you'll use this pattern everywhere.

Try it

Make a ProjectCard that takes title, description and link props, and use it three times in App.jsx with your own projects. Then wrap each one in a Card component that uses children.


Next: React Part 4: Remember things with state

reactjavascriptwebdevbeginners

Join WIK to like and reply to DevNotes and see more like this.