Props — These Are " Packages " with Data
If components are functions, then Props (Properties) are the arguments of these functions. But in React, these aren't just " variables " — they're a real social contract between components.
1. Analogy: Legal Contract
When you create a UserCard component, you're essentially signing a contract:
- You say: " I promise to draw a beautiful user card. "
- Condition: " But you (the Parent) must pass me a name (
name) and photo (avatar). " If the parent violates the contract and passes nothing — the card will " break " or be empty.
2. Golden Rule: Props Are a " Gift "
Imagine someone gave you a phone as a gift. You can use it, download apps, make calls. But you cannot retroactively change the fact that you were given exactly this model.
In React, props are IMMUTABLE (unchangeable).
- A child receives a
propsobject and can only read from it. - ❌ Forbidden: Writing
props.name = "Ivan". React will immediately throw an error or simply ignore it. - Why? Because the one who created the data (the Parent) is responsible for it. If you allow a child to change props — chaos will begin in the application, and no one will know where the " real " information is.
3. Destructuring: The Magic of Clean Code
To avoid writing the word props. a hundred times, we use destructuring. This allows you to immediately " extract " the needed data right in the function declaration.
// Instead of (props)
function Welcome({ name, role = "Guest" }) {
return (
<div>
<h1>Hello, {name}!</h1>
<p>Your status: {role}</p>
</div>
);
}
Important about role = "Guest": This is the default value. If the parent forgets to pass role, the component won't show emptiness but will substitute the word " Guest " . This makes your code resilient to errors.
4. Props Are Not Just Text
You can pass anything that exists in JavaScript via props:
- Objects and arrays: Product list, profile data.
- Numbers and booleans:
count={10},isActive={true}. - Functions (Most important!): A parent can give a child a function (e.g.,
onDelete). When the child presses their button, they'll call this function, and deletion will happen above, at the parent level.
Well-designed props make your components universal. You write Button once, then use it 100 times with different names, colors, and functions throughout the site.