What Are Props?
Props (short for "properties") are used to pass data from a parent component to a child component in React. Props make components reusable and dynamic.
Props are:
- Immutable (Cannot be changed inside the component)
- Passed from parent to child
- Read-only
Using Props in Functional Components
Example: Passing Props to a Child Component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return <Greeting name="Alice" />;
}
export default App;
The Greeting
component receives the name
prop and displays "Hello, Alice!"
.
Using Props in Class Components (Older Method)
import React, { Component } from "react";
class Greeting extends Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
function App() {
return <Greeting name="Alice" />;
}
export default App;
Functional components are preferred for props handling.
Default Props
You can set default values for props using defaultProps.
Example: Default Props in Functional Components
function Greeting({ name = "Guest" }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
or using defaultProps
:
Greeting.defaultProps = {
name: "Guest",
};
Props as Objects (props
vs. Destructuring)
Props are passed as an object. You can access them directly using props
or destructure them.
Using props
object:
function User(props) {
return <h1>{props.name} is {props.age} years old</h1>;
}
Using destructuring:
function User({ name, age }) {
return <h1>{name} is {age} years old</h1>;
}
Destructuring is preferred for cleaner code.
Passing Functions as Props
Example: Child Component Calls Parent Function
function Button({ onClick }) {
return <button onClick={onClick}>Click Me</button>;
}
function App() {
const handleClick = () => {
alert("Button clicked!");
};
return <Button onClick={handleClick} />;
}
export default App;
The onClick
function is passed from App
to Button
.
Passing Components as Props (children
Prop)
Props can also include React elements or components.
Example: Using children
Prop
function Card({ children }) {
return <div className="card">{children}</div>;
}
function App() {
return (
<Card>
<h2>Title</h2>
<p>This is content inside the card.</p>
</Card>
);
}
export default App;
The children
prop lets you wrap elements inside a component.
Props vs. State (Key Differences)
Feature | Props ( Passed from Parent) | State ( Internal to Component) |
---|---|---|
Mutability | Immutable | Mutable |
Where Defined? | Parent Component | Inside the Component |
How to Update? | Cannot be changed | Use useState()
|
Summary
- Props allow data flow from parent to child.
- Props are immutable (read-only).
- Props can be objects, functions, or even React elements.
-
Use
children
prop to pass JSX inside components.
Top comments (0)