Handling and Displaying Dynamic Data
Hello, students! In the previous topic, we learned about the rendering process in React.
Here, we will learn about manipulating and displaying dynamic data in React.
Dynamic data is information that can change over time.
For example, a list of products or a logged-in user are examples of dynamic data.
To handle and display dynamic data in React, we need to use state and props.
State
State is an object that stores private data of the component.
The data in the state can be modified by the component but cannot be accessed by other components.
To access the state, we use the this.state
property.
For example, the following code defines a state to store a list of products:
class MyComponent extends React.Component { state = { products: [ { name: "Product 1", price: 100, }, { name: "Product 2", price: 200, }, ], }; render() { return ( <div> <ul> {this.state.products.map((product) => ( <li key={product.id}>{product.name}</li> ))} </ul> </div> ); } }
This code renders a list of products in the user interface.
The data for the list of products is stored in the state of the MyComponent
component.
Props
Props are data passed to a component from another component.
The data from props can be accessed by any component that receives them.
To access the props, we use the this.props
property.
For example, the following code defines a component that receives a list of products as props:
const MyComponent = (props) => { return ( <div> <ul> {props.products.map((product) => ( <li key={product.id}>{product.name}</li> ))} </ul> </div> ); };
This code renders a list of products in the user interface.
The data for the list of products is passed to the MyComponent
component as props.
In the next module, we will learn about JSX.
JSX is an extension of JavaScript that allows writing HTML code within JavaScript.
JSX makes writing React components easier and more readable.
I hope you’re excited to learn more about JSX!
Conclusion
In today’s topic, we learned about how to handle and display dynamic data in React.
We learned about state and props, which are two ways to store and access dynamic data in React.
I hope you’ve understood how to handle and display dynamic data in React.
Until then, keep studying!