Guide to Using Props in React

react props guide
10 November 2024

When talking about programming with React, one of the most important concepts to learn is the use of Props.

In simple terms, Props in React are used to pass data and information to components.

Essentially, Props provide us with the ability to reuse our components; that is, we can define them once and then use them in different places with varying data.

One of the key benefits of using Props is that we can easily pass different data to a component and that component can interact with the same data correctly.

Now let's look at a code example to better understand the concept of Props.

<!-- React Component.js -->
import React from "react";

function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

function App() {
return (
<div>
<Greeting name="Ali" />
<Greeting name="Sara" />
</div>
);
}

export default App;

Line by Line Explanation of the Code

import React from "react";
This line imports the React library, which is necessary for working with React code.
function Greeting(props)
Here, we define a component called Greeting that receives props as input.
return <h1>Hello, {props.name}!</h1>;
This line renders the component which generates a welcoming message with the passed name.
function App()
Here, we define a main or parent component named App that includes other components.
<Greeting name="Ali" />
With this line, we call the Greeting component with the name prop set to "Ali".
<Greeting name="Sara" />
Similarly, this uses the Greeting component again with a different name prop set to "Sara".
export default App;
This line allows the App component to be the default export so that it can be used in other files.

FAQ

?

How can you create a component using Props in React?

?

What are the benefits of using Props in React?