What are Props in React?
In React, props (short for properties) are used to pass data from one component to another. They allow you to pass dynamic content to your components and are a fundamental concept in React development.
Think of props as function arguments or HTML attributes. They enable you to customize components with different values based on the inputs passed to them.
How to Use Props #
To pass props to a React component, you use the same syntax as HTML attributes. Here’s a simple example to demonstrate this.
Example: Passing a prop to a component
Let’s create a simple component that takes a prop called brand
.
const Car = (props) => {
return <h2>I am a {props.brand}!</h2>;
};
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car brand="Ford" />);
In this example, the Car
component receives a brand
prop and displays the brand name in an h2
tag.
Passing Props from Parent to Child Component #
Props are used to pass data from a parent component to a child component. For example, we can send the brand
data from a Garage component to a Car component.
Example: Passing props between components
function Car(props) {
return <h2>I am a {props.brand}!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Here, the Garage component passes the brand
prop to the Car component, where it is displayed.
Using Variables with Props #
You can also pass variables instead of static string values to your components.
Example: Passing a variable as a prop
function Car(props) {
return <h2>I am a {props.brand}!</h2>;
}
function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={carName} />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
In this example, the carName
variable is passed as the brand
prop to the Car component.
Passing Objects as Props #
You can also pass complex data like objects as props to components.
Example: Passing an object as a prop
function Car(props) {
return <h2>I am a {props.brand.model}!</h2>;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={carInfo} />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Here, the carInfo
object is passed as the brand
prop to the Car component, which then accesses the model
property of the object.
Important Note on Props #
React props are read-only. This means that once a prop is passed into a component, you cannot change its value within the component. If you try to modify a prop, React will throw an error.
Want to learn React with an instructor, either offline or online? Find experienced tutors near you and join Coaching Wallah—completely free for students!
Leave your comment