1. What are Props? 🎁
Props (short for "properties") are how you pass data from a parent component down to a child component. They allow you to customize a component and make it reusable with different information.
If you think of components as JavaScript functions (which they are!), then props are like the arguments you pass to that function.
2. Passing and Receiving Props
You pass props to a child component using syntax that looks just like HTML attributes. The child component then receives all these props as a single object.
Let's modify our `Greeting` component from the last module to accept a `name` prop.
Step 1: Pass the prop from the parent (`App`)
In the `App` component, when we use `
function App() {
return (
<div>
{/* We are passing a prop named "name" with the value "Alice" */}
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
Step 2: Receive the prop in the child (`Greeting`)
The `Greeting` function will now receive an object as its first argument. By convention, we call this object `props`. We can then access the data using dot notation (e.g., `props.name`).
// The "props" object is automatically passed to our component
function Greeting(props) {
// We access the "name" property from the props object
return <h1>Hello, {props.name}!</h1>;
}
When this code runs, React will render two greetings: "Hello, Alice!" and "Hello, Bob!". We've successfully reused our `Greeting` component with different data.
3. A More Practical Example
You can pass any kind of JavaScript data as props, including strings, numbers, arrays, and even other components. Let's create a `UserProfile` component that takes multiple props.
function UserProfile(props) {
return (
<div className="user-profile">
<img src={props.avatarUrl} alt={props.name} />
<h2>{props.name}</h2>
<p>Age: {props.age}</p>
</div>
);
}
function App() {
const user1 = {
name: "Clark Kent",
age: 30,
avatar: "https://i.pravatar.cc/150?u=clark"
};
return (
<div>
<UserProfile
name="Diana Prince"
age={200}
avatarUrl="https://i.pravatar.cc/150?u=diana"
/>
<UserProfile
name={user1.name}
age={user1.age}
avatarUrl={user1.avatar}
/>
</div>
);
}
// Don't forget to render the App!
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);