Understanding React Props
If you're just a few months into coding and diving into React, you might have encountered the term "props." It’s short for "properties," but what does that actually mean? Think of props as a way to pass information between components in React. It’s like giving a custom gift to a friend—the gift (prop) can be anything, and the friend (component) uses it however they need!
Let’s break it down step by step.
What Are Props in React?#
In React, components are like building blocks. Props are how we pass data between those blocks. If a parent component wants to share data with a child component, props come to the rescue.
Here’s a simple analogy:
- Parent Component: Think of it as a parent who has information (data) to share.
- Child Component: Think of it as a child who receives and uses that information.
How Do Props Work?#
Props are passed to child components like attributes in HTML. For example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="John" />;
}What’s Happening Here?
Appis the parent component.Greetingis the child component.- The parent passes a prop called
namewith a value of"John". - Inside
Greeting, the value ofprops.nameis used to displayHello, John!.
Breaking It Down Further#
1. Declaring a Child Component#
When you create a child component, you define a parameter—usually called props—to access the data passed from the parent.
Example:
function DisplayMessage(props) {
return <p>{props.message}</p>;
}2. Passing Props from the Parent#
When using the child component in the parent, you provide the data inside attributes:
function App() {
return <DisplayMessage message="Welcome to React!" />;
}Common Props Use Cases#
1. Displaying Dynamic Data#
Props allow you to send different pieces of data to your components.
function UserProfile(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Age: {props.age}</p>
</div>
);
}
function App() {
return <UserProfile name="Alice" age={25} />;
}2. Reusing Components#
You can pass different props to the same component to reuse it for different purposes.
function Button(props) {
return <button>{props.label}</button>;
}
function App() {
return (
<div>
<Button label="Submit" />
<Button label="Cancel" />
</div>
);
}Key Rules About Props#
-
Props Are Read-Only:
You cannot modify props inside the child component. They are immutable, meaning you can only read and use them. -
Props Can Be Any Data Type:
Props can include strings, numbers, objects, arrays, or even functions.function DisplayInfo(props) { return <p>{props.details.name} is {props.details.age} years old.</p>; } function App() { const info = { name: "Sam", age: 30 }; return <DisplayInfo details={info} />; } -
Default Props:
If no value is passed, you can set default values for props.function Welcome(props) { return <h1>Welcome, {props.name}!</h1>; } Welcome.defaultProps = { name: "Guest", };
All the Code You Need to Practice#
Live code runner
Props