0% completed
In this section, you’ll learn about props in React, an essential concept for passing data between components. By the end of this lesson, you’ll understand what props are, how they work, and how to use them effectively in your React apps.
Props is short for properties. In simple terms, props are like the characteristics of a component that allow you to pass data between them. Think of props as input values for a component, which tell it how to behave or what to display.
This ability to pass dynamic data makes components more reusable and flexible. Here’s a quick example:
function Welcome(props) { return <h1>Hello, {props.name}!</h1>; }
In this case, props.name
is passed to the component, customizing the message displayed.
Now, let’s look at how props are passed from one component to another.
To pass data to a child component, you define attributes in the component tag (just like HTML). These attributes hold the values that will be passed as props.
For example:
function App() { return <Welcome name="Alice" age={25} />; }
In this case:
App
component passes two props (name="Alice"
and age={25}
) to the Welcome
component.Once props are passed, the receiving component accesses them via the function parameters. You can use destructuring to make the code cleaner.
Example:
function Welcome({ name, age }) { return ( <> <h1>Hello, {name}!</h1> <p>You are {age} years old.</p> </> ); }
Here:
Welcome
component destructures name
and age
directly from the props
object.You can also destructure props directly in the function’s parameter list, which is a cleaner and more concise way to access specific properties.
For example:
function Welcome({ name, age }) { return <h1>Hello, {name}. You are {age} years old!</h1>; }
This allows you to access name
and age
directly, rather than using props.name
and props.age
.
Let’s put everything together in a full example that demonstrates how props are passed and received, so you can get a clearer view:
import React from "react"; function Welcome({ name, age }) { return ( <> <h1>Hello, {name}!</h1> <p>You are {age} years old.</p> </> ); } function App() { return ( <div> <Welcome name="Alice" age={25} /> <Welcome name="Bob" age={30} /> </div> ); } export default App;
In this example:
App
component renders two instances of the Welcome
component.name
and age
to each instance.Welcome
component receives these props and dynamically displays the data.Props are powerful because they allow you to:
.....
.....
.....