Working with Props
In React, props allow you to pass data from a parent component to a child component. Props are read-only, making them great for passing data down the component tree.
To pass props, you can include them as attributes when rendering a component. The child component can then access the props via this.props
.
Here's an example of a child component Welcome
that receives a name
prop and displays a welcome message:
1import React, { Component } from 'react';
2
3class Welcome extends Component {
4 render() {
5 return <h1>Hello, {this.props.name}!</h1>;
6 }
7}
8
9// Example usage:
10<Welcome name="John" />
11<Welcome name="Jane" />
In the example above, the Welcome
component is rendered twice with different values for the name
prop. Each instance of the Welcome
component will display a personalized welcome message based on the value of the name
prop.
This allows you to create reusable components that can accept different data dynamically. By passing props down the component tree, you can easily configure and customize child components based on the parent component's state or data.
As a frontend developer, understanding how to work with props in React is essential for building dynamic and interactive user interfaces. By leveraging the power of props, you can create modular and reusable components that can be easily composed and manipulated.
xxxxxxxxxx
// import React, { Component } from 'react';
// class Welcome extends Component {
// render() {
// return <h1>Hello, {this.props.name}!</h1>;
// }
// }
// Example usage:
// <Welcome name="John" />
// <Welcome name="Jane" />