Day 6: Dynamic React Components using Props
React utilizes a component-based architecture that enables developers to create reusable and modular UI elements. A fundamental concept in React, props, plays a crucial role in managing and passing data between components.
Working with Props in React
Props, short for properties, pass data from a parent component to its child components. Props are read-only and cannot be modified directly by the receiving component. Props provide a way to make components dynamic and reusable. To pass props to a component, we pass them as attributes when rendering the component. This allows us to configure the behaviour and appearance of child components based on the data provided by the parent component.
export const Productcard = (props) => {
const { image, title, price} = props.data;
return (
<div>
<h1>{title}</h1>
<p>{description}</p>
</div>
);
};
What is JSON?
JSON (JavaScript Object Notation) is a lightweight data interchange format for storing and exchanging data. It consists of key-value pairs and is widely supported by different programming languages and APIs.
We can work with JSON data that needs to be passed into components for rendering dynamic content. This data can come from third-party APIs or be read from external files. In our case, we entered some data manually in a JSON file. Passing JSON values into React components allows us to create flexible and reusable UI components that can be dynamically populated with data.
Once the JSON file is ready, we import it to our react application.
Import ProductsData from ‘./../product-data.json’
After importing the JSON data, we can access its values like any other JavaScript object. JSON data is typically structured as nested objects or arrays. To access specific values, we can traverse the JSON structure using dot notation or array indexing.
Traversing JSON
Traversing the JSON structure using array indexing refers to accessing and navigating through the elements of a JSON object or array by specifying the index position of the desired element.
export const DisplayProducts=()=>{
return(
<>
<div className="container-fluid">
<div className="row row-cols-1 row-cols-md-4 g-4">
{ProductsData.map((product) =>(
<Productcard
key={product.id}
image={product.product_image_url}
title={product.product_title}
price={product.product_price}
/>
))}
</div>
</div>
</>
)
}
Thanking our mentor Bikash Karki for today's lesson, I conclude this article.