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:
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:
{!inStock && <p>...</p>} shows that paragraph only when inStock is false. React Part 6 covers this pattern properly.
Now one component serves every product:
Default values
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:
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:
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
Join WIK to like and reply to DevNotes and see more like this.