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.
Props are like arguments in function calls. They are used to customize the behavior of a React component.
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.
Props are used in both functional and class components. Here's an example of how to use props in a functional component:
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 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.
Here's an example of a parent component passing a prop to a child component:
function ParentComponent() {
let name = "React User";
return <ChildComponent name={name} />;
}function ChildComponent(props) {
return <h1>Welcome, {props.name}!</h1>;
}In this example, the ParentComponent is passing the name prop to the ChildComponent.
What is the role of props in React?
We can also pass functions as props. Here's an example:
let greet = (name) => `Hello, ${name}!`;
function ParentComponent() {
return <ChildComponent greetFunction={greet} />;
}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.
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! 🎉