0% found this document useful (0 votes)
8 views50 pages

Adding Event Listeners Made Easy

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 50

Advance React

Adding Event Listeners made easy

Watch video 1 and 2 from the following link and add event listeners to the button.

<button onClick={()=>{console.log("hi")}}>Delete</button>

By writing onClick={clickHandler}, you're passing a reference to the function

When you write onClick={clickHandler()}, you're actually calling the function immediately
when the component renders, and whatever is returned from clickHandler is then assigned
as the event handler. This is not what you want. You want to assign the clickHandler function
itself as the event handler, so it will be called when the button is clicked, not when the
component renders.

// import './Expense.css';

import './ExpenseItem.css';
import ExpenseDate from './ExpenseDate';

import Card from '../UI/Card';

function ExpenseItem(props){
const clickHandler = ()=>{
console.log("hello!")
}

return (
<Card className="expense-item">
<ExpenseDate date={props.date}/>
<div className="expense-item__description">
<h2>{props.title}</h2>
<div className="expense-item__price">{props.amount}</div>
</div>
<button onClick={clickHandler}>Delete</button>
</Card>

)
}
export default ExpenseItem;

in this I learn how to add evet listener.

https://github.com/pandey0801/Adding-Event-Listeners-/upload/main

03/02/2024

Manipulating the DOM - React States


003 How Component Functions Are Executed.
Que. Tell me why didnt the title update . Write your answer here
Ans. because react never repeat step. once it exeut it over the step

004 Working with State


Que. What dataType does useState function return? What does each index mean
ans.useState function in React returns an array with two elements:
The first element is the current state value.
The second element is a function that allows you to update the state.
Que. Why do we have to use setTitel() to update title ? Why dont we simply do title = 'new Title' ?
Ans. because setTitel() is a function. we can't simply assign title = 'new Title'. so we use setTitle('new
Title')
Que. According to you setTitle is an async function or synchronous function. Answer this on the basis of
that the console.log(title) below it gives old value even though you call setTitle() before. Think!!!!
Ans. UseState is asynchronous. you call setTitle(newValue) to update the state, the actual state update
and re-render may not happen immediately. It will happen at an optimal time determined by React's
reconciliation process. This is why you might see the old state value logged immediately after calling
setTitle(newValue). The new state value will be reflected in the component after the state update and re-
render have completed.

005 A Closer Look at the useState Hook


Que. When we click on button only the corresponding title gets updated. What do you think is the reason
Ans. Each instance of Component maintains its own state managed by useState. When you click the
"Update Title" button in one instance, only that instance's state will be updated, and only that instance will
re-render with the new title. The other instance remains unchanged.

Que. [Super Important Question] - When does useState initialize the state.
Ans. In React, the useState hook initializes the state when the component is first rendered.
When you call useSate(initialValue) , React sets up the initial state with the provided initialVlaue. This
happens during the initial render of the component.

Que. [Super Important Question] - What happens when you update the state using setTitle
Ans. When you update the state using SetTitle():
1. The state value is updated to newValue.
2. React schedules a re-render of the component.
3. During re-render, the UI reflects the new state value.
4. React efficiently updates the DOM to reflect the changes.
// import './Expense.css';

import React, {useState} from 'react';


import './ExpenseItem.css';
import ExpenseDate from './ExpenseDate';

import Card from '../UI/Card';

function ExpenseItem(props){

const [amount, setTitle] = useState(props.amount);

const clickHandler = ()=>{


setTitle("100");
// console.log(amount);
};

return (
<Card className="expense-item">
<ExpenseDate date={props.date}/>
<div className="expense-item__description">
<h2>{props.title}</h2>
<div className="expense-item__price">{amount}</div>
</div>
<button onClick={clickHandler}>Delete</button>
</Card>
)
}
export default ExpenseItem;

Functional Class
Components Components

A functional component is just a plain A class component requires you to


JavaScript pure function that accepts extend from React. Component and
props as an argument and returns a create a render function that returns
React element(JSX). a React element.

It must have the render() method


There is no render method used in
returning JSX (which is syntactically
functional components.
similar to HTML)
In React, a hook is a special function that allows you to add additional features to functional components.
Hooks were introduced in React 16.8 as a way to use state and other React features without writing a
class component.

because react never repeat step (render). once it executed it over the step
1.useState function in React returns an array with two elements:

1. The first element is the current state value.


2. The second element is a function that allows you to update the state.
2.because setTitel() is a function. we can't simply assign title = 'new Title'. so we
use setTitle('new Title')
3.UseState is asynchronous. you call setTitle(newValue) to update the state, the
actual state update and re-render may not happen immediately. It will happen at an
optimal time determined by React's reconciliation process. This is why you might
see the old state value logged immediately after calling setTitle(newValue). The new
state value will be reflected in the component after the state update and re-render
have completed.
4. Each instance of Component maintains its own state managed by useState. When
you click the "Update Title" button in one instance, only that instance's state will be
updated, and only that instance will re-render with the new title. The other instance
remains unchanged.
5.The use of const here is related to the destructuring assignment syntax in
JavaScript. When you call useState, it returns an array with two elements: the
current state value and the function to update that state. Using array destructuring,
you can assign these two elements . we are giving the value to function
6.In React, the useState hook initializes the state when the component is first
rendered.
When you call useSate(initialValue) , React sets up the initial state with the provided
initialVlaue. This happens during the initial render of the component. The state is
then managed by React and persists across re-renders.
7.When you update the state using SetTitle():

1. The state value is updated to newValue.


2. React schedules a re-render of the component.
3. During re-render, the UI reflects the new state value.
4. React efficiently updates the DOM to reflect the changes.

https://github.com/pandey0801/Manipulating-the-DOM---React-States

Creating your own first Component

007 Adding Form Inputs


008 Listening to User Input

ExpenseForm.js
import './ExpenseForm.css'

const ExpenseForm = () =>


{

const titleChangeHandeler = (event) =>


{
console.log(event.target.value);
}
return(
<form>
<div className='new-expense__controls'>
<div className='new-expense__controls'>
<label>Title</label>
<input type='text' onChange={titleChangeHandeler}/>
</div>

<div className='new-expense__controls'>
<label>Amount</label>
<input type='number' min="0.01" step="0.01"/>
</div>

<div className='new-expense__controls'>
<label>Date</label>
<input type='date' min="2019-01-01" max="2022-12-31"/>
</div>

<div className='new-expense__actions'>
<button type='submit'>Add Expense</button>
</div>
</div>
</form>
)
}

export default ExpenseForm;

ExpenseForm.js

import './NewExpense.css';
import ExpenseForm from './ExpenseForm';

const NewExpense = () =>


{
return(
<div className='new-expense'>
<ExpenseForm/>
</div>
)
}

export default NewExpense;


Expenseform.css

.new-expense__controls {
display: flex;
flex-wrap: wrap;
gap: 1rem;
margin-bottom: 1rem;
text-align: left;
}

.new-expense__control label {
font-weight: bold;
margin-bottom: 0.5rem;
display: block;
}

.new-expense__control input {
font: inherit;
padding: 0.5rem;
border-radius: 6px;
border: 1px solid #ccc;
width: 20rem;
max-width: 100%;
}

.new-expense__actions {
text-align: right;
}

NewExpense.css

.new-expense {
background-color: #a892ee;
padding: 1rem;
margin: 2rem auto;
width: 50rem;
max-width: 95%;
border-radius: 12px;
text-align: center;
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.25);
}

.new-expense button {
font: inherit;
cursor: pointer;
padding: 1rem 2rem;
border: 1px solid #40005d;
background-color: #40005d;
color: white;
border-radius: 12px;
margin-right: 1rem;
}

.new-expense button:hover,
.new-expense button:active {
background-color: #510674;
border-color: #510674;
}

.new-expense button.alternative {
color: #220131;
border-color: transparent;
background-color: transparent;
}

.new-expense button.alternative:hover,
.new-expense button.alternative:active {
background-color: #ddb3f8;
}
06Stepping into the shoes of an Interviewer
https://github.com/pandey0801/Creating-your-own-first-Component

Lets introduce state inside the new Component

DELIVERABLE

1. Add a state called enteredtitle and update this whenever the user changes the title.
2. Similarly add a state called enteredAmount and update this whenever the user changes the
amount
3. Similarly add a state called enteredDate and update this whenever the Date changes.

009 working with multiple states

import React, {useState} from 'react';


import './ExpenseForm.css'

const ExpenseForm = () =>


{
const [enteredTitle, setEnterTitle] =useState('');
const [enteredAmount, setEnteredAmount]= useState('');
const [enteredDate,setEnteredDate] = useState('');

const titleChangeHandeler = (event) =>{


setEnterTitle(event.target.value)
// console.log(event.target.value);
}

const amountChangeHandler = (event)=>{


setEnteredAmount(event.target.value)
}

const dateChangeHandler=(event)=>{
setEnteredDate(event.target.value)
}

return(
<form>
<div className='new-expense__controls'>
<div className='new-expense__controls'>
<label>Title</label>
<input type='text' onChange={titleChangeHandeler}/>
</div>

<div className='new-expense__controls'>
<label>Amount</label>
<input type='number' min="0.01" step="0.01"
onChange={amountChangeHandler}/>
</div>

<div className='new-expense__controls'>
<label>Date</label>
<input type='date' min="2019-01-01" max="2022-12-31"
onChange={dateChangeHandler}/>
</div>

<div className='new-expense__actions'>
<button type='submit'>Add Expense</button>
</div>
</div>
</form>
)
}
export default ExpenseForm;
Design patterns with state

Please explain why we use this


setUserInput({ ...userInput, title: event.target.value})
setUserInput({ ...userInput, title: event.target.value})

we using this because we wat latest state for update. that why we passing uerInput to the
function. and copy that

010 Using One State Instead

011 Updating State That Depends On The Previous State

Submitting the forms

When the user clicks on the submit button create an object and log it on the screen. Its very
easy. TRY IT BY YOURSELF.
const submitHandler=(event)=>{
event.preventDefault();
console.log("clicke");
console.log(enteredTitle);
console.log(enteredAmount);
console.log(enteredDate);
}

<div className='new-expense__actions'>
<button type='submit' onClick={submitHandler}>Add Expense</button>
</div>

012 Handling Form Submission

import React, {useState} from 'react';


import './ExpenseForm.css'

const ExpenseForm = () =>


{

const [enteredTitle, setEnterTitle] =useState('');


const [enteredAmount, setEnteredAmount]= useState('');
const [enteredDate,setEnteredDate] = useState('');

const titleChangeHandeler = (event) =>{


setEnterTitle(event.target.value)
// console.log(enteredTitle);
// console.log(setEnterTitle(event.target.value));

// console.log(setEnterTitle(event.target.value));
// console.log(setEnterTitle)

const amountChangeHandler = (event)=>{


setEnteredAmount(event.target.value)
}

const dateChangeHandler=(event)=>{
setEnteredDate(event.target.value)
}

const submitHandler=(event)=>{
event.preventDefault();
const expenseData = {
Titel: enteredTitle,
amount: enteredAmount,
date: new Date (enteredDate)
}
console.log(expenseData);
}

return(
<form onSubmit={submitHandler}>
<div className='new-expense__controls'>
<div className='new-expense__controls'>
<label>Title</label>
<input type='text' onChange={titleChangeHandeler}/>
</div>

<div className='new-expense__controls'>
<label>Amount</label>
<input type='number' min="0.01" step="0.01"
onChange={amountChangeHandler}/>
</div>

<div className='new-expense__controls'>
<label>Date</label>
<input type='date' min="2019-01-01" max="2022-12-31"
onChange={dateChangeHandler}/>
</div>

<div className='new-expense__actions'>
<button type='submit'>Add Expense</button>
</div>
</div>
</form>
)
}

export default ExpenseForm;

https://github.com/pandey0801/Submitting-the-forms

07 Stepping into the shoes of an Interviewer


05/02/2024

08 Making the expense form input visible on screen


013 Adding Two-Way Binding

Two-way data binding is a technique that allows data to flow in both directions between a user
interface (UI) and the application's state. This means that when a user changes the value of a UI
element, the state is updated automatically, and vice versa.
import React, { useState } from 'react';

function TwoWayBindingExample() {
// Initialize state with an empty string
const [value, setValue] = useState('');

// Event handler to update the state when input value changes


const handleChange = (event) => {
setValue(event.target.value);
};

return (
<div>
{/* Input field controlled by state */}
<input
type="text"
value={value}
onChange={handleChange}
/>
{/* Display the value from state */}
<p>Value: {value}</p>
</div>
);
}

export default TwoWayBindingExample;

the value attribute of the input element is set to value, which is controlled by React state.
When the user types in the input field, the onChange event handler updates the state with the
new value. As a result, changes made by the user in the input field are immediately reflected in
the displayed value

014 Child-to-Parent Component Communication (Bottom-up)

Child-to-parent component communication in React involves passing data from a child


component to its parent component.

Parent code
function ParentComponent() {
const handleDataFromChild = (data) => {
console.log("Data from child:", data);
};
return <ChildComponent onData={handleDataFromChild} />;
}

Child code
function ChildComponent({ onData }) {
const sendDataToParent = () => {
const data = "Hello from child";
onData(data);
};

return <button onClick={sendDataToParent}>Send Data</button>;


}

callback functions are often used for child-to-parent component communication, allowing child
components to pass data or trigger actions in their parent components.

015 Lifting The State Up

"Lifting state up" is a common pattern in React where you move the state from a lower-level
component to a higher-level component in the component tree. This pattern allows you to
share state between components and manage it in a single location, typically in a common
ancestor of the components that need access to the state.

ExpenseFrom.js

import React, {useState} from 'react';


import './ExpenseForm.css'
const ExpenseForm = (props) =>
{

const [enteredTitle, setEnterTitle] =useState('');


const [enteredAmount, setEnteredAmount]= useState('');
const [enteredDate,setEnteredDate] = useState('');

const titleChangeHandeler = (event) =>{


setEnterTitle(event.target.value)
// console.log(enteredTitle);
// console.log(setEnterTitle(event.target.value));

// console.log(setEnterTitle(event.target.value));
// console.log(setEnterTitle)

const amountChangeHandler = (event)=>{


setEnteredAmount(event.target.value)
}

const dateChangeHandler=(event)=>{
setEnteredDate(event.target.value)
}

const submitHandler=(event)=>{
event.preventDefault();
const expenseData = {
Titel: enteredTitle,
amount: enteredAmount,
date: new Date (enteredDate)
}
props.onSaveExpenseData(expenseData);

setEnterTitle('')
setEnteredAmount('')
setEnteredDate('')
}

return(
<form onSubmit={submitHandler}>
<div className='new-expense__controls'>
<div className='new-expense__controls'>
<label>Title</label>
<input type='text'
value={enteredTitle}
onChange={titleChangeHandeler}/>
</div>

<div className='new-expense__controls'>
<label>Amount</label>
<input type='number'
min="0.01"
step="0.01"
value={enteredAmount}
onChange={amountChangeHandler}/>
</div>

<div className='new-expense__controls'>
<label>Date</label>
<input type='date'
min="2019-01-01"
max="2022-12-31"
value={enteredDate}
onChange={dateChangeHandler}/>
</div>

<div className='new-expense__actions'>
<button type='submit'>Add Expense</button>
</div>
</div>
</form>
)
}

export default ExpenseForm;

NewExpense.js
import './NewExpense.css';

import ExpenseForm from './ExpenseForm';

const NewExpense = (props) =>


{
const saveExpenseDataHandler= (enteredExpenseData) =>{
const expenseData = {
...enteredExpenseData,
id:Math.random().toString()
};
// console.log(expenseData);
props.onAddExpense(expenseData);
}

return(
<div className='new-expense'>
<ExpenseForm onSaveExpenseData ={saveExpenseDataHandler}/>
</div>
)
}

export default NewExpense;

App.js
// import logo from './logo.svg';
// import './App.css';
// import './components/Expense.css'

import './components/Expenses/Expense.css'
import ExpenseItem from "./components/Expenses/ExpenseItem";
import Card from './components/UI/Card';
import NewExpense from './components/NewExpense/NewExpense';

const App = () => {

const expenses = [
{
id: 'e1',
title: 'Toilet Paper',
amount: 94.12,
date: new Date(2020, 7, 14),
},
{ id: 'e2',
title: 'New TV',
amount: 799.49,
date: new Date(2021, 2, 12)
},
{
id: 'e3',
title: 'Car Insurance',
amount: 294.67,
date: new Date(2021, 2, 28),
},
{
id: 'e4',
title: 'New Desk (Wooden)',
amount: 450,
date: new Date(2021, 5, 12),
},
];

const AddExpenseHandler = expense =>{


console.log("in reat");
console.log(expense);
}

return (
<div>
<NewExpense onAddExpense={AddExpenseHandler} />

<Card className="expenses">

<ExpenseItem title={expenses[0].title} amount={expenses[0].amount}


date={expenses[0].date}></ExpenseItem>
<ExpenseItem title={expenses[1].title} amount={expenses[1].amount}
date={expenses[1].date}></ExpenseItem>
<ExpenseItem title={expenses[2].title} amount={expenses[2].amount}
date={expenses[2].date}></ExpenseItem>
<ExpenseItem title={expenses[3].title} amount={expenses[0].amount}
date={expenses[0].date}></ExpenseItem>

</Card>
</div>
);
}

export default App;

Task details
One common problem with the website is that the input forms still hold onto the old value.
Check video 13 from following link to understand how you can solve this problem.
[Very Important Video] - Watch video 14 and 15 from above link and solve the problem of dynamically
updating the expense array whenever the user fills the input form. Code along with the udemy trainer and
answer the following.

1. Can you tell the exact flow of data from ExpenseForm component to Expense Component as per the
trainer
2. Why did we have to lift the state up from NewExpense component to App component. Why cant we
directly talk between NewExpense and Expense Component?

Deliverable
Can you now utilize the addExpenseHandler function in APP.js in such a way that it starts showing
dynamically in the UI. Try it by yourself. It is super simple now.

Push the code to git and upload the commit ID

1.we getting the data from ExpenseForm. we passing the data to NewExpense from
ExpenseForm. and passing the data from ExpenseForm to App.js

2.bacause we want all the data in one place. we move the state from a lower-level
component to a higher-level component in the component tree. This pattern allows
you to share state between components and manage it in a single location.

https://github.com/pandey0801/Making-the-expense-form-input-visible-on-screen

https://github.com/pandey0801/Making-the-expense-form-input-visible-on-screen

06/02/2024

PlaceHolder - Adding a filter which doesnt work on the expense tracker

016 Controlled vs Uncontrolled Components & Stateless vs Stateful Components


Controlled vs Uncontrolled Components

Controlled Components:

 Form elements are controlled by React state.


 Value changes trigger state updates and re-renders.
 Provides more control and flexibility over form data.
 Preferred for most React applications.
 Controlled components refer to components where form elements such as input,
textarea, and select are controlled by React state.
 The value of the form element is controlled by React state and is updated only
through state setters.
 Changes to the form element trigger state updates, and React re-renders the
component with the new value.

Uncontrolled Components:

 Form elements manage their own state internally using the DOM.
 Value changes do not trigger state updates or re-renders.
 Useful for integrating with non-React code or third-party libraries.
 State management delegated to the DOM.

Stateless (Functional) Components:

 Also known as functional components.


 Defined as JavaScript functions that accept props as input and return JSX.
 Purely presentational, focused on rendering UI based on props.
 Typically used for simple, presentational components that do not need to manage state
or lifecycle.

Stateful (Class-based) Components:

 Also known as class components.


 Defined as JavaScript classes that extend React.Component.
 Have internal state and can manage state using setState method.
 Can have lifecycle methods to hook into component lifecycle events.
 Used for more complex components that require state management and lifecycle hooks.

Filter.js

// import React from 'react';

import './ExpenseFilter.css';

const ExpensesFilter = (props) => {

const dropdownChangeHandler= (event)=>{


props.onChangeFilter(event.target.value);
}
return (
<div className='expenses-filter'>
<div className='expenses-filter__control'>
<label>Filter by year</label>
<select value={props.select} onChange={dropdownChangeHandler}>
<option value='2022'>2022</option>
<option value='2021'>2021</option>
<option value='2020'>2020</option>
<option value='2019'>2019</option>
</select>
</div>
</div>
);
};

export default ExpensesFilter;


ExpenseFilter.css

.expenses-filter {
color: white;
padding: 0 1rem;
align-items: center;
}

.expenses-filter__control {
/* display: flex; */
width: 100%;
align-items: center;
justify-content: space-between;
margin: 1rem 0;
}

.expenses-filter label {
font-weight: bold;
margin-bottom: 0.5rem;
}

.expenses-filter select {
font: inherit;
padding: 0.5rem 3rem;
font-weight: bold;
border-radius: 6px;
}

App.js
// import logo from './logo.svg';
// import './App.css';
// import './components/Expense.css'

// import React, {useState} from 'react';


// import { useState } from "react";
import React, {useState} from 'react';

import './components/Expenses/Expense.css'
import ExpenseItem from "./components/Expenses/ExpenseItem";
import Card from './components/UI/Card';
import NewExpense from './components/NewExpense/NewExpense';

import ExpensesFilter from './components/Expenses/ExpenseFilter';

const App = () => {

const expenses = [
{
id: 'e1',
title: 'Toilet Paper',
amount: 94.12,
date: new Date(2020, 7, 14),
},
{ id: 'e2',
title: 'New TV',
amount: 799.49,
date: new Date(2021, 2, 12)
},
{
id: 'e3',
title: 'Car Insurance',
amount: 294.67,
date: new Date(2021, 2, 28),
},
{
id: 'e4',
title: 'New Desk (Wooden)',
amount: 450,
date: new Date(2021, 5, 12),
},
];

const AddExpenseHandler = expense =>{


console.log("in reat");
console.log(expense);
}

const [filteredYear,setFilteredYear] = useState('2020');


const filterChangeHandler= selectedYear =>{
setFilteredYear(selectedYear);
console.log(filteredYear);
};

return (
<div>
<NewExpense onAddExpense={AddExpenseHandler} />

<ExpensesFilter selected={filteredYear}
onChangeFilter={filterChangeHandler}/>
{/* <ExpensesFilter/> */}

<Card className="expenses">

<ExpenseItem title={expenses[0].title} amount={expenses[0].amount}


date={expenses[0].date}></ExpenseItem>
<ExpenseItem title={expenses[1].title} amount={expenses[1].amount}
date={expenses[1].date}></ExpenseItem>
<ExpenseItem title={expenses[2].title} amount={expenses[2].amount}
date={expenses[2].date}></ExpenseItem>
<ExpenseItem title={expenses[3].title} amount={expenses[0].amount}
date={expenses[0].date}></ExpenseItem>

</Card>
</div>
);
}

export default App;

https://github.com/pandey0801/PlaceHolder---Adding-a-filter-which-doesnt-work-on-the-
expense-tracker
Rendering Expenses with performance optimisations
001 Module Introduction
002 Rendering Lists of Data
{expenses.map(expense => (
<ExpenseItem
key={expense.id}
title={expense.title}
amount={expense.amount}
date={expense.date}
/>
))}

Watch video 1 and 2 from the following link and code along with the Udemy trainer and answer the
following.

1. Why did the Udemy trainer even convert the code. Why doesn't he use ExpenseItem Component -> 4
times for showing 4 expenses. What do you think is the reason?

Watch video 3 from above link , code along with the udemy trainer and answer the following

1. Why does the trainer uses state and not update the old expense variable. If you update the old expense
variable like this expenses.push(expense). Why does this not work?

Watch video 4 from above link, code along with the udemy trainer and answer the following.[Very
important for performance enhacement]

1. What happens when you don't use keys ?


2. What is the advantage of using keys?
3. Why you should not use index as keys?

ans
1. using dynamic rendering. we don't know how many list item does Expenses have
2. for updating the state we will use usestate and separator operator to copy the old array item list
3. When you don't use keys in a list of elements in React, it can lead to issues with performance, state
management, and component reusability
4. using keys in React provides several benefits, including improved rendering performance, stable
component identity, prevention of reordering issues, optimized DOM operations, and enhanced
component reusability
5. using the index of an element as its key may seem convenient, it is generally not recommended in React
due to its lack of stability, limited usefulness, potential performance implications, accessibility concerns,
and potential for bugs and errors

https://github.com/pandey0801/Rendering-Expenses-with-performance-optimisations

7/2/2024

Implementing the filter feature


// import logo from './logo.svg';
// import './App.css';
// import './components/Expense.css'

// import React, {useState} from 'react';


// import { useState } from "react";
import React, {useState} from 'react';

import './components/Expenses/Expense.css'
import ExpenseItem from "./components/Expenses/ExpenseItem";
import Card from './components/UI/Card';
import NewExpense from './components/NewExpense/NewExpense';

import ExpensesFilter from './components/Expenses/ExpenseFilter';

const DUMMY_EXPENSES = [
{
title: 'Toilet Paper',
amount: 94.12,
date: new Date(2020, 7, 14),
id: 'e1',
},
{
title: 'New TV',
amount: 799.49,
date: new Date(2021, 2, 12),
id: 'e2',
},
{
title: 'Car Insurance',
amount: 294.67,
date: new Date(2021, 2, 28),
id: 'e3',
},
{
title: 'New Desk (Wooden)',
amount: 450,
date: new Date(2021, 5, 12),
id: 'e4',
},
];

const App = () => {

const [expenses,setEXpenses] = useState(DUMMY_EXPENSES);

const AddExpenseHandler = expense =>{


// console.log("in reat");
// console.log(expense);
setEXpenses((preExpense)=>{
return [expense, ...preExpense];
})
}

const [filteredYear,setFilteredYear] = useState('2020');


const filterChangeHandler= selectedYear =>{
setFilteredYear(selectedYear);

// const wantItem = expenses.filter(item=>


// selectedYear==item.date

// )
};

// const arr = expenses.map(exp=>{


// return exp.date.getFullYear().toString()
// })
// // console.log(arr);

// // {arr==filteredYear?console.log("true"):console.log("false")}

// const fl = arr.filter(x=>{
// return x==filteredYear
// })

// // console.log(fl);
// console.log(filteredYear);

const filteredExpenses = expenses.filter(exp=>{


return exp.date.getFullYear().toString() === filteredYear;
});

// console.log(filteredExpenses);

return (
<div>
<NewExpense onAddExpense={AddExpenseHandler} />

<Card className="expenses">

<ExpensesFilter selected={filteredYear}
onChangeFilter={filterChangeHandler}/>

{/* {console.log(expenses)} */}

{filteredExpenses.map(expense => (
<ExpenseItem
title={expense.title}
amount={expense.amount}
date={expense.date}
key={expense.id}
/>
))}

</Card>
</div>
);
}

export default App;

https://github.com/pandey0801/Implementing-the-filter-feature

Conditional Rendering

005 Outputting Conditional Content


// import logo from './logo.svg';
// import './App.css';
// import './components/Expense.css'

// import React, {useState} from 'react';


// import { useState } from "react";
import React, {useState} from 'react';

import './components/Expenses/Expense.css'
import ExpenseItem from "./components/Expenses/ExpenseItem";
import Card from './components/UI/Card';
import NewExpense from './components/NewExpense/NewExpense';

import ExpensesFilter from './components/Expenses/ExpenseFilter';

const DUMMY_EXPENSES = [
{
title: 'Toilet Paper',
amount: 94.12,
date: new Date(2020, 7, 14),
id: 'e1',
},
{
title: 'New TV',
amount: 799.49,
date: new Date(2021, 2, 12),
id: 'e2',
},
{
title: 'Car Insurance',
amount: 294.67,
date: new Date(2021, 2, 28),
id: 'e3',
},
{
title: 'New Desk (Wooden)',
amount: 450,
date: new Date(2021, 5, 12),
id: 'e4',
},
];

const App = () => {

const [expenses,setEXpenses] = useState(DUMMY_EXPENSES);

const AddExpenseHandler = expense =>{


// console.log("in reat");
// console.log(expense);
setEXpenses((preExpense)=>{
return [expense, ...preExpense];
})
}

const [filteredYear,setFilteredYear] = useState('2020');


const filterChangeHandler= selectedYear =>{
setFilteredYear(selectedYear);

// const wantItem = expenses.filter(item=>


// selectedYear==item.date

// )
};

// const arr = expenses.map(exp=>{


// return exp.date.getFullYear().toString()
// })
// // console.log(arr);
// // {arr==filteredYear?console.log("true"):console.log("false")}

// const fl = arr.filter(x=>{
// return x==filteredYear
// })

// // console.log(fl);
// console.log(filteredYear);

const filteredExpenses = expenses.filter(exp=>{


return exp.date.getFullYear().toString() === filteredYear;
// console.log(exp.date.getFullYear().toString())
});

// console.log(filteredExpenses);

return (
<div>
<NewExpense onAddExpense={AddExpenseHandler} />

{/* <ExpensesFilter/> */}

<Card className="expenses">

<ExpensesFilter selected={filteredYear}
onChangeFilter={filterChangeHandler}/>

{filteredExpenses.length===0 && <p>No Elemnet</p>}


{filteredExpenses.length===1 && <p>Only single Expense here. Please add
more...</p>}
{filteredExpenses.length>0 && filteredExpenses.map(expense => (
<ExpenseItem
title={expense.title}
amount={expense.amount}
date={expense.date}
key={expense.id}
/>
))}

{/* {filteredExpenses.map(expense => (


<ExpenseItem
title={expense.title}
amount={expense.amount}
date={expense.date}
key={expense.id}
/>
))} */}
</Card>
</div>
);
}

export default App;


</div>)
}

return(
<div className='expenses-list'>
{props.item.map((expense) => (
<ExpenseItem
title={expense.title}
amount={expense.amount}
date={expense.date}
key={expense.id}
/>
))}
</div>
)
}

export default ExpensesList


ExpenseList.css

.expenses-list {
list-style: none;
padding: 0;
}

.expenses-list__fallback {
color: white;
text-align: center;
}

App.js

// import logo from './logo.svg';


// import './App.css';
// import './components/Expense.css'

// import React, {useState} from 'react';


// import { useState } from "react";
import React, {useState} from 'react';

import './components/Expenses/Expense.css'
// import ExpenseItem from "./components/Expenses/ExpenseItem";
import Card from './components/UI/Card';
import NewExpense from './components/NewExpense/NewExpense';
import ExpensesFilter from './components/Expenses/ExpenseFilter';
import ExpensesList from './components/Expenses/ExpensesList';

const DUMMY_EXPENSES = [
{
title: 'Toilet Paper',
amount: 94.12,
date: new Date(2020, 7, 14),
id: 'e1',
},
{
title: 'New TV',
amount: 799.49,
date: new Date(2021, 2, 12),
id: 'e2',
},
{
title: 'Car Insurance',
amount: 294.67,
date: new Date(2021, 2, 28),
id: 'e3',
},
{
title: 'New Desk (Wooden)',
amount: 450,
date: new Date(2021, 5, 12),
id: 'e4',
},
];

const App = () => {

const [expenses,setEXpenses] = useState(DUMMY_EXPENSES);

const AddExpenseHandler = expense =>{


// console.log("in reat");
// console.log(expense);
setEXpenses((preExpense)=>{
return [expense, ...preExpense];
})
}

const [filteredYear,setFilteredYear] = useState('2020');


const filterChangeHandler= selectedYear =>{
setFilteredYear(selectedYear);

// const wantItem = expenses.filter(item=>


// selectedYear==item.date

// )
};

// const arr = expenses.map(exp=>{


// return exp.date.getFullYear().toString()
// })
// // console.log(arr);

// // {arr==filteredYear?console.log("true"):console.log("false")}

// const fl = arr.filter(x=>{
// return x==filteredYear
// })

// // console.log(fl);
// console.log(filteredYear);

const filteredExpenses = expenses.filter(exp=>{


return exp.date.getFullYear().toString() === filteredYear;
// console.log(exp.date.getFullYear().toString())
});

// console.log(filteredExpenses);

return (
<div>
<NewExpense onAddExpense={AddExpenseHandler} />

{/* <ExpensesFilter/> */}

<Card className="expenses">

<ExpensesFilter selected={filteredYear}
onChangeFilter={filterChangeHandler}/>

<ExpensesList item={filteredExpenses}/>
{/* {filteredExpenses.length===0 && <p>No Elemnet</p>}
{filteredExpenses.length===1 && <p>Only single Expense here. Please add
more...</p>}
{filteredExpenses.length>0 && filteredExpenses.map(expense => (
<ExpenseItem
title={expense.title}
amount={expense.amount}
date={expense.date}
key={expense.id}
/>
))} */}

{/* {filteredExpenses.map(expense => (


<ExpenseItem
title={expense.title}
amount={expense.amount}
date={expense.date}
key={expense.id}
/>
))} */}
</Card>
</div>
);
}

export default App;


https://github.com/pandey0801/Conditional-Rendering

DIY - Challenges on Conditional Rendering


expenseFrom.js

import './NewExpense.css';
import ExpenseForm from './ExpenseForm';
import React, {useState} from 'react';
const NewExpense = (props) =>
{
const [showCustomComponent, setShowCustomComponent] = useState(false);

const saveExpenseDataHandler= (enteredExpenseData) =>{


const expenseData = {
...enteredExpenseData,
id:Math.random().toString()
};
// console.log(expenseData);
props.onAddExpense(expenseData);

setShowCustomComponent(false);
}

const handleButtonClick = () => {


setShowCustomComponent(true);
};

const stopButtonHandler =()=>{


setShowCustomComponent(false);
}

return(
<div className='new-expense'>

{!showCustomComponent && <button onClick={handleButtonClick}>Add NEw


Expense</button>}
{showCustomComponent && <ExpenseForm
onSaveExpenseData ={saveExpenseDataHandler}
onCancel={stopButtonHandler}
/>}
</div>
)
}

export default NewExpense;


ExpenseForm.js
import React, {useState} from 'react';
import './ExpenseForm.css'

const ExpenseForm = (props) =>


{
// console.log(props);

const [enteredTitle, setEnterTitle] =useState('');


const [enteredAmount, setEnteredAmount]= useState('');
const [enteredDate,setEnteredDate] = useState('');

const titleChangeHandeler = (event) =>{


setEnterTitle(event.target.value)
// console.log(enteredTitle);
// console.log(setEnterTitle(event.target.value));

// console.log(setEnterTitle(event.target.value));
// console.log(setEnterTitle)

const amountChangeHandler = (event)=>{


setEnteredAmount(event.target.value)
}

const dateChangeHandler=(event)=>{
setEnteredDate(event.target.value)
// console.log(event.target.value);

// console.log(enteredDate);

const submitHandler=(event)=>{
event.preventDefault();
const expenseData = {
title: enteredTitle,
amount: enteredAmount,
date: new Date (enteredDate)
// data: enteredDate
}
// console.log(expenseData);

// Props.onSaveExpenseData(expenseData);
// console.Consolelog(Props.onSave(expenseData))
// Props.onSave(expenseData);

// const data = "Hello from child";


props.onSaveExpenseData(expenseData);

setEnterTitle('')
setEnteredAmount('')
setEnteredDate('')
}

return(
<form onSubmit={submitHandler}>
<div className='new-expense__controls'>
<div className='new-expense__controls'>
<label>title</label>
<input type='text'
value={enteredTitle}
onChange={titleChangeHandeler}/>
</div>

<div className='new-expense__controls'>
<label>Amount</label>
<input type='number'
min="0.01"
step="0.01"
value={enteredAmount}
onChange={amountChangeHandler}/>
</div>

<div className='new-expense__controls'>
<label>Date</label>
<input type='date'
// min="2019-01-01"
// max="2022-12-31"
value={enteredDate}
onChange={dateChangeHandler}/>
</div>

<div className='new-expense__actions'>
<button type='button'
onClick={props.onCancel}>Cancel</button>
<button type='submit'>Add Expense</button>
</div>
</div>
</form>
)
}

export default ExpenseForm;

https://github.com/pandey0801/DIY---Challenges-on-Conditional-Rendering

Chart App

https://github.com/pandey0801/Chart-App

You might also like