Props Introduction 🎯

beginner
18 min

Props Introduction 🎯

Welcome to our deep dive into React JS! Today, we're going to explore an essential concept - Props.

Props, short for properties, are a way to pass data from a parent component to a child component in React. Let's understand why we need props and how they work with a simple example.

What are Props? 📝

Props are like arguments in function calls. They are used to customize the behavior of a React component.

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

In the above example, Greeting is a functional component that accepts a props object. The name is a prop we are passing to this component.

How to use Props? 💡

Props are used in both functional and class components. Here's an example of how to use props in a functional component:

Functional Component with Props

javascript
function Greeting(props) { return <h1>Hello, {props.name}!</h1>; } // Using the Greeting component <Greeting name="John Doe" />

In the above example, we're passing John Doe as a prop to the Greeting component.

Now, let's see how to use props in a class component:

Class Component with Props

javascript
class Greeting extends React.Component { render() { return <h1>Hello, {this.props.name}!</h1>; } } // Using the Greeting component <Greeting name="Jane Doe" />

In this example, we're using a class component and passing Jane Doe as a prop to the Greeting component.

Passing Props from Parent to Child 🎯

Here's an example of a parent component passing a prop to a child component:

Parent Component

javascript
function ParentComponent() { let name = "React User"; return <ChildComponent name={name} />; }

Child Component

javascript
function ChildComponent(props) { return <h1>Welcome, {props.name}!</h1>; }

In this example, the ParentComponent is passing the name prop to the ChildComponent.

Quick Quiz
Question 1 of 1

What is the role of props in React?

Passing Function as Props 💡

We can also pass functions as props. Here's an example:

Parent Component with a Function as a Prop

javascript
let greet = (name) => `Hello, ${name}!`; function ParentComponent() { return <ChildComponent greetFunction={greet} />; }

Child Component using a Function as a Prop

javascript
function ChildComponent(props) { return <h1>{props.greetFunction("React User")}</h1>; }

In this example, the ParentComponent is passing the greet function as a prop to the ChildComponent.

Quick Quiz
Question 1 of 1

Can we pass a function as a prop in React?

That's it for today! Props are a powerful tool in React, and understanding them is essential for building complex React applications. In the next lesson, we'll dive deeper into state management.

Happy coding! 🎉