[React.js] - Part 4. React Props

Ace Lennox
In React, props (short for "properties") are used to pass data from one component to another, similar to function arguments in JavaScript. Props allow components to be reusable and dynamic. This guide explains React props with simplified examples.
What Are React Props?
React props are:
Arguments: Passed to components via HTML-like attributes.
Read-only: Props cannot be modified inside the component that receives them.
Syntax Example
To pass props to a component, use the same syntax as HTML attributes:
const myElement = <Car brand="Toyota" />;
The component receives props as an object:
function Car(props) {
return <h2>I drive a {props.brand}!</h2>;
}
Example 1: Passing Static Props
Let’s create a simple example where a Car
component receives a brand
prop:
import ReactDOM from "react-dom/client";
function Car(props) {
return <h2>I drive a {props.brand}!</h2>;
}
function Garage() {
return (
<div>
<h1>Welcome to my garage</h1>
<Car brand="Toyota" />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Garage />);
In this example, the Garage
component passes the brand
prop to the Car
component.
Example 2: Passing Variables as Props
Props can also accept variables, making your components dynamic.
function Car(props) {
return <h2>I drive a {props.brand}!</h2>;
}
function Garage() {
const carName = "Honda";
return (
<div>
<h1>Welcome to my garage</h1>
<Car brand={carName} />
</div>
);
}
Here, carName
is passed as the brand
prop to the Car
component.
Example 3: Passing Objects as Props
You can also pass entire objects as props for more complex data.
function Car(props) {
return <h2>I drive a {props.details.model} made by {props.details.brand}!</h2>;
}
function Garage() {
const carDetails = { brand: "Ford", model: "Mustang" };
return (
<div>
<h1>Welcome to my garage</h1>
<Car details={carDetails} />
</div>
);
}
In this case, the Car
component uses both brand
and model
from the carDetails
object.
Key Rules of Props
Props Are Read-only: You cannot modify props inside the receiving component. Attempting to do so will throw an error.
Dynamic Values: Props can accept variables, objects, arrays, or any valid JavaScript expression wrapped in curly braces
{}
.Component Reusability: Props make components more flexible and reusable.
Summary
Props are an essential part of React, enabling components to receive dynamic data and become reusable. Whether you pass strings, variables, or objects, props allow you to build more robust and maintainable applications.
Experiment with these examples to understand how props can make your React components dynamic and versatile!
Source Code
The complete source code for this project is available on GitHub