Component Communication: Passing Data with Props
Discover how to build reusable and dynamic components by passing data from parent to child.
/* Starting the journey into component communication... */
What Are Props?
In React, props (short for "properties") are the mechanism for passing data from a parent component down to a child component. Think of them as arguments to a function or attributes to an HTML tag. They are read-only, meaning a child component should never modify the props it receives.
Parent to Child: The Data Flow
React has a unidirectional data flow. This means data always flows in one direction: downwards from parent to child. This makes the logic of your application easier to understand and debug because you know exactly where the data is coming from.
Syntax in Action: Passing & Receiving
You pass props to a child component like HTML attributes: <ChildComponent name="Alice" />
. The child then receives these props as a single object argument. You can access them via `props.name` or, more commonly, by destructuring them: function ChildComponent({ name })
.
The Result: Reusable & Dynamic Components
The primary benefit of props is creating reusable components. You can design a generic component, like a `UserProfile`, and then use it multiple times with different data (props) to display information for different users without rewriting the component's structure.
Practice Zone
Interactive Test 1: Identify the Roles
You have an `App` (parent) rendering a `UserProfile` (child). Match the code to its role.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Complete the Code
Rellena los huecos en cada casilla.
// Parent Component function App() { return <Message ="Hello World!" /> } // Child Component function Message({ text }) { return <p></p> }
Practice Example: Code Editor
Create a `Product` component that accepts `name` (string) and `price` (number) as props and displays them in an `h2` and `p` tag respectively.
Props in Practice
Props are the lifeblood of React component architecture. They allow you to build a tree of components that can communicate and share data effectively. Let's see some advanced use cases.
1. Passing State as Props
A parent component often manages state and passes it down to children as props. When the parent's state updates, React re-renders the parent, which then passes the new props to its children, causing them to re-render with the new data.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<Display count={count} /> { /* State passed as prop */ }
</div>
);
}
function Display({ count }) { // Child receives state as prop
return <p>The count is: {count}</p>;
}
2. Passing Functions as Props (Callbacks)
To let a child communicate back to a parent (e.g., on a button click), you can pass a function from the parent to the child as a prop. The child can then call this function, which will execute in the parent's scope, allowing it to update the parent's state.
function Parent() {
const [message, setMessage] = useState('');
// This function is passed down
const handleChildClick = () => {
setMessage('Button in child was clicked!');
}
return <Child onButtonClick={handleChildClick} />
}
function Child({ onButtonClick }) {
return <button onClick={onButtonClick}>Click Me</button>
}
3. The `children` Prop
React has a special prop called `children`. It contains whatever content is placed between the opening and closing tags of a component. This is perfect for creating generic "wrapper" or "layout" components.
// Card component can wrap any content
function Card({ children }) {
return <div className="card">{children}</div>;
}
// Usage in parent
<Card>
<h1>Card Title</h1>
<p>This will be passed as props.children.</p>
</Card>
Practical Takeaway: Understanding how to pass data, state, and functions via props is essential for building anything beyond a simple React application. It is the core of component composition.
Props Glossary
- Props
- Short for "properties," it's an object containing data passed from a parent component to a child component. Props are read-only.
- Parent / Child Component
- In a component tree, a parent is a component that renders another component (the child). Data flows from parent to child.
- Unidirectional Data Flow
- The principle that data in a React application flows in a single direction—down the component tree from parent to child via props.
- Prop Drilling
- A situation where props are passed down through multiple layers of nested components that don't need the data themselves, just to get it to a deeply nested child. This is often a sign to consider state management solutions.
- `props.children`
- A special prop that contains the content passed between the opening and closing tags of a component instance, allowing for component composition.