React Meals
React Meals
app.js
function App() {
return (
<Fragment>
<h2>Let's get started!</h2>
<Header></Header>
</Fragment>
);
}
HeaderCardButton.js
import CartIcon from "../Cart/CartIcon";
import classes from './HeaderCartButton.module.css'
Its important that you try doing this by yourself. Its ok if you don't follow the best design patterns
and file structure.
If stuck for very long watch video 3 and 4 from the above link.
Once done, push the code to git and upload the commit id
const DUMMY_MEALS = [
{
id: 'm1',
name: 'Sushi',
description: 'Finest fish and veggies',
price: 22.99,
},
{
id: 'm2',
name: 'Schnitzel',
description: 'A german specialty!',
price: 16.5,
},
{
id: 'm3',
name: 'Barbecue Burger',
description: 'American, raw, meaty',
price: 12.99,
},
{
id: 'm4',
name: 'Green Bowl',
description: 'Healthy...and green...',
price: 18.99,
},
];
return (
// <section className={classes.mealsList}>
<section className={classes.meals}>
<ul>
{mealsList}
</ul>
</section>
);
}
export default AvailableMeals;
Once the code is complete, push the code to git and upload commit ID.
MealItem.js
</div>
</li>
);
}
export default MealItem;
https://github.com/pandey0801/Making-the-Items-visible
Adding a Form
Task details
Deliverable [TRY DOING THIS BY YOURSELF]
1. You have to add a form for user to select number of quantity of item he want to order.
2. Also add an "ADD Button"
3. On clicking on the add button nothing should happen now. We will add logic later on
If stuck for very long watch video 7 from the following link.
MealItemForm.js
import classes from './MealItemForm.module.css'
import Input from '../UI/Input';
const MealItemForm = props =>
{
return <from className={classes.form}>
{/* <input / */}
<Input label ="Amount" input={{
id: 'amount',
type: 'number',
min: "1",
max: '5',
step: '1',
defaultValue: '1'
}} />
<button>+ ADD</button>
</from>
};
https://github.com/pandey0801/Adding-a-Form
Deliverable
1. You had learnt about React.createportal() previously . Use that to build this
https://drive.google.com/file/d/1_3zEu9cRIno287crU7CS-QSGWk1AfNLQ/view?usp=sharing. It is pretty
simple i feel.
2. Hard code the contents of the cart.
3. When the user comes to the page the page should directly open .
4. You don't have to make the close and order button work.
5. We will do the functionality portion in the next task
If stuck for long watch video 9 and 10 from the following link .
Card.js
return (
<Fragment>
{ReactDOM.createPortal(<Backdrop onClose={props.onClose} />,
portalElement)}
{ReactDOM.createPortal(
<ModalOverlay>{props.children}</ModalOverlay>,
portalElement
)}
</Fragment>
);
};
https://github.com/pandey0801/Making-a-hard-Coded-Cart-without-any-Functionality
Cart open and close
Task details
Deliverable
1. When the user clicks on the cart icon , the cart should open up
https://drive.google.com/file/d/13TchLhjm_Ubj5Co5bKXVzLQXUaTqyfaW/view?usp=sharing. [TRY IT BY
YOPURSELF]
2. This could be simply done by using hooks, try it by yourself.
3. Now when the user clicks on the close button , the cart should close. Watch video 11 from the
following link to understand how to do it.
app.js
import Header from "./componenets/Layout/Header";
import { Fragment , useState } from "react";
import Meals from "./componenets/Meals/Meals";
import Cart from "./componenets/Cart/Cart";
function App() {
// console.log("sdds");
const [cartIsShow, setCartIsShow] = useState(false);
return (
<Fragment>
{cartIsShow && <Cart onCloseCart={hideCartHandler}/>}
<Header onShowCart={showCartHandler}/>
<Meals />
</Fragment>
);
}
header.js
import { Fragment } from "react";
import mealsImage from '../../assets/meals.jpg';
import classes from './Header.module.css';
import HeaderCardButton from "./HeaderCardButton";
cart.js
import classes from './Cart.module.css'
import Modal from '../UI/Modal';
modal.js
import { Fragment } from 'react';
import ReactDOM from 'react-dom';
return (
<Fragment>
{ReactDOM.createPortal(<Backdrop onClose={props.onClose} />,
portalElement)}
{ReactDOM.createPortal(
<ModalOverlay>{props.children}</ModalOverlay>,
portalElement
)}
</Fragment>
);
};
CartContext.js
import React from 'react';
CartProvider.js
const defaultCartState = {
items: [],
totalAmount: 0,
};
if (existingCartItem) {
const updatedItem = {
...existingCartItem,
amount: existingCartItem.amount + action.item.amount,
};
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
} else {
updatedItems = state.items.concat(action.item);
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount,
};
}
if (action.type === 'REMOVE') {
const existingCartItemIndex = state.items.findIndex(
(item) => item.id === action.id
);
const existingItem = state.items[existingCartItemIndex];
const updatedTotalAmount = state.totalAmount - existingItem.price;
let updatedItems;
if (existingItem.amount === 1) {
updatedItems = state.items.filter(item => item.id !== action.id);
} else {
const updatedItem = { ...existingItem, amount: existingItem.amount - 1 };
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount
};
}
return defaultCartState;
};
const cartContext = {
items: cartState.items,
totalAmount: cartState.totalAmount,
addItem: addItemToCartHandler,
removeItem: removeItemFromCartHandler,
};
return (
<CartContext.Provider value={cartContext}>
{props.children}
</CartContext.Provider>
);
};
function App() {
// console.log("sdds");
const [cartIsShow, setCartIsShow] = useState(false);
const showCartHandler = () =>
{
setCartIsShow(true);
}
return (
<CartProvider>
{cartIsShow && <Cart onCloseCart={hideCartHandler}/>}
<Header onShowCart={showCartHandler}/>
<Meals />
</CartProvider>
);
}
https://github.com/pandey0801/DIY--Implementing-the-cart-Itemns-page
Test
const defaultCartState = {
items: [],
totalAmount: 0,
};
);
const existingCartItem = state.items[existingCartItemIndex];
let updatedItems;
if (existingCartItem) {
const updatedItem = {
...existingCartItem,
amount: existingCartItem.amount + action.item.amount,
};
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
} else {
updatedItems = state.items.concat(action.item);
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount,
};
}
if (action.type === 'REMOVE') {
const existingCartItemIndex = state.items.findIndex(
(item) => item.id === action.id
);
const existingItem = state.items[existingCartItemIndex];
const updatedTotalAmount = state.totalAmount - existingItem.price;
let updatedItems;
if (existingItem.amount === 1) {
updatedItems = state.items.filter(item => item.id !== action.id);
} else {
const updatedItem = { ...existingItem, amount: existingItem.amount - 1 };
updatedItems = [...state.items];
updatedItems[existingCartItemIndex] = updatedItem;
}
return {
items: updatedItems,
totalAmount: updatedTotalAmount
};
}
return defaultCartState;
};
const cartContext = {
items: cartState.items,
totalAmount: cartState.totalAmount,
addItem: addItemToCartHandler,
removeItem: removeItemFromCartHandler,
};
console.log(cartContext)
return (
<CartContext.Provider value={cartContext}>
{props.children}
</CartContext.Provider>
);
};
1. What are the 4 things that the component cares about. Explain each one of them.
2. What is Virtual DOM.
3. How does Virtual DOM diffing make React fast
State: State represents the internal data of a component that can change over time. Unlike
props, state is mutable and managed within the component itself. Components can initialize
state, update it based on user interactions or other events, and trigger re-renders to reflect the
updated state.
Context: Context provides a way to share data across the component tree without manually
passing props down through each level of nesting. It allows components to subscribe to a
context and access the data it provides. Context is useful for providing global data, such as
themes, user authentication, or language preferences, to multiple components in an
application.
Virtual DOM (Document Object Model): The Virtual DOM is a lightweight representation of
the actual DOM in memory. React uses the Virtual DOM to optimize rendering performance
by comparing changes in the Virtual DOM and selectively updating the actual DOM only
where necessary. This approach minimizes browser reflows and repaints, leading to faster
rendering and better user experience.
2.Virtual DOM Tree Creation: When a React component renders, it creates a corresponding
Virtual DOM tree, which mirrors the structure of the actual DOM but is constructed using
plain JavaScript objects.
Efficient Updates: When changes are made to a component's state or props, React doesn't
immediately update the actual DOM. Instead, it first updates the Virtual DOM tree with the
new state or props.
Reconciliation: React then compares the updated Virtual DOM tree with the previous one
using a process called reconciliation. It identifies the differences (or "diffs") between the two
trees efficiently, thanks to its diffing algorithm.
Minimal DOM Updates: After identifying the differences, React determines the minimal set
of changes needed to update the actual DOM. It only applies these changes to the real DOM,
avoiding unnecessary re-renders and updates.
3.Virtual DOM is a lightweight copy of the actual DOM, used by React to efficiently update
the user interface. When changes occur, React compares the current Virtual DOM with the
previous one, identifying the minimal set of updates needed to reflect the changes. This
process, known as "diffing,"
1.."It all comes down to state change." What does the trainer mean by this.
2..Why does "APP RUNNING" get printed whenever we click on Toggle Paragragh button
1..when we change a state it will change the virtual DOM then Virtual DOM change the actual DOM
2..because it re rending the component
1.the <p> tag flash because the <p> added in the actual DOM
2.because when every the parent component render the child should also render that why we getting
DemoOutput get reevaluated
3.no the <p> not tag flash. because the hardcoded value and actual DOM is not changing
2.If your component gets lots of different props often or has complicated rendering
logic, it's best not to use React.memo. This means if the component's appearance
changes frequently or if it has many nested parts, memoization might not help much
and could even slow things down.
3.Demooutput component getting the props (false) value which not changing.
Myparagraph is always calling and changing value
1.How does useCallback solve the above problem of preventing reevaluation whenever we click on
"Toggle Paragraph" button.Please explain the logic.
2.What is the second argument of usecallback? What does it do?
1.In React, useCallback is a hook used to store a function and memoize it, meaning it
remembers the function instance between renders. This helps optimize performance
by preventing unnecessary re-creations of the function on every render, especially
when passing functions as dependencies to other hooks or components. By
specifying dependencies, useCallback ensures that the function is only recreated
when those dependencies change, reducing unnecessary re-renders and improving
the efficiency of your React application. const memoizedCallback = useCallback(
() => {
// Function body
},
[/* Dependency array */]
);
2.The second argument of useCallback is an array of dependencies. This argument
specifies the values that the callback function depends on. If any of these
dependencies change, useCallback will re-create the function. If the dependencies
remain the same between renders, useCallback will return the same memoized
function instance, optimizing performance by avoiding unnecessary re-renders.
Watch video 7
1.allowToggle is a sate change that changes over time and is used inside the
callback function, then it should be included in the dependency list of useCallback.
This ensures that the callback is recreated whenever allowToggle changes,
guaranteeing that the latest value of allowToggle is captured inside the callback.
2.If allowToggle is not included in the dependency list of useCallback, the callback
function will not be recreated when allowToggle changes. This means that the
callback will continue to reference the initial value of allowToggle, leading to
incorrect behavior when allowToggle is updated. As a result, the component may not
work as expected because it relies on the updated value of allowToggle to determine
its behavior.