An open API service indexing awesome lists of open source software.

https://github.com/learnwithfair/react-js

React-JS with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]
https://github.com/learnwithfair/react-js

learnwithfair rahatul-rabbi react reactjs

Last synced: 10 months ago
JSON representation

React-JS with [learnwithfair, Learn with fair, Rahatul Rabbi, Md Rahatul Rabbi ,rahatulrabbi]

Awesome Lists containing this project

README

          

## REACT-JS TUTORIAL

Thanks for visiting my GitHub account!

**React** is a free and open-source front-end JavaScript library for building user interfaces based on components. It is maintained by Meta and a community of individual developers and companies. React can be used to develop single-page, mobile, or server-rendered applications with frameworks like Next.js

## Source Code (Download)

- [Click Here](https://mega.nz/file/oeNEASAS#xGJJKPpuyQ4sQO6IbCW8e91v7pD3e2_7NcgD9y9_OXo)
- [Click Here](https://mega.nz/folder/UWkxEK7R#flijF8l7WD48VtUtGJ4q_A)

## Required Software (Download)

- VS Code, Download (LTS) ->https://code.visualstudio.com/download
- Node, Download-> https://nodejs.org/en/download
- React Developer tools extension for google, firefox, edge
- Extension: ES7 react, JS JSX snippets + “editior.snipperSuggestions”: “top”, react developer tools, material theme, setup eslint and prettier

## ========== Environment Setup ==========

1. Instal Node.js
2. To verify installation into command form by node -v or node --version

## How to use the template?

- clone to your local machine
- npm install --force
- npm start
- Or, create and run react app with npx

```js
// create react app command
npx create-react-app appName

// If any error occurs
npm install npm -g

// run react app command
cd appName
npm start
```

## Project Features

| |
| :-------------------------------------: |
| Project Components |
| ![features](/images/react-features.jpg) |

## Tutorial

[![Watch the video](https://github.com/learnwithfair/canva-design/blob/main/Thumbnail/react-js-first-part.png)](https://youtube.com/playlist?list=PLXjydF9SaxY4i7GdEqL7bAMhh2t1JihDo&si=c0qZ2UPRx2dvTARJ)

# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.\
You will also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

# React Documentation

- Prerequisites: HTML, CSS, Javascript
- [React.js Official Site](https://reactjs.org/)

## Table of Contents

1. [Basic React.js Topics](#1-basic-reactjs-topics)

[1.1 Introduction to React](#11-introduction-to-react)

[1.2 JSX and JS Expression](#12-jsx-and-js-expression)

[1.3 Component](#13-component)

[1.4 Adding CSS Styling](#14-adding-css-styling)

[1.5 Props and destructuring](#15-props-and-destructuring)

[1.6 Mapping components](#16-mapping--rednering-components)

[1.7 Proptotypes](#17-proptypes)

[1.8 Conditional rendering](#18-conditional-rendering)

[1.9 developer tools, react and font-awesome icons](#19-developer-tools-react-and-font-awesome-icons)

[1.10 Adding Interactivity - event & event handler](#110-adding-interactivity---event--event-handler)

[1.11 useState Hooks](#111-usestate-hooks)

[1.12 Forms and Controlled components](#112-forms-and-controlled-components)

[1.13 data passing: child to parent component, state lifting](#113-data-passing-child-to-parent-component-state-lifting)

[1.14 useRef hook - Uncontrolled component](#114-useref-hook---uncontrolled-component)

2. [Intermediate React.js Topics](#2-intermediate-reactjs-topics)

[2.1 life cycle methods of a class component](#21-life-cycle-methods-of-a-class-component)

[2.2 useEffect Hook](#22-useeffect-hook)

[2.3 useReducer Hook](#23-usereducer-hook)

[2.4 Routing](#24-routing)

[2.5 CRUD Operations - http methods - user management app](#25-crud-operations---http-methods---user-management-app)

[2.6 Optimization memo, useCallback and useMemo](#26-optimization-reactmemo-usecallback-usememo)

[2.7 props drilling, useContext Hook](#27-props-drilling-usecontext-hook)

3. [Advanced React.js Topics]()

4. Assignments

[Assignment 1: product listing App](https://github.com/anisul-Islam/react-assignment-1-products-listing-app)

[Assignment 2: Counter App](https://github.com/anisul-Islam/react-assignment-2-counter-app)

[Assignment 3: Add New Product](https://github.com/anisul-Islam/react-assignment-3-add-new-product)

[Assignment 4: fetch products](https://github.com/anisul-Islam/react-assignment-4-fetch-products)

[Assignment-5]()

## 1. Basic React.js Topics

### [1.1 Introduction to React](https://youtu.be/fRXL0X2WSK4)

#### What is React?

React is an open-source JavaScript library for building user interfaces. It was developed in 2013 and is maintained by Facebook. React is known for its performance, flexibility, and component-based architecture, which allows developers to build reusable UI components and efficiently manage the state of an application.

#### Why React / Features of React.js

![React](images/Untitled-2023-10-07-1651.png)

Here are some key features and concepts associated with React:

1. **Component-Based:** React applications are built using components, which are self-contained, reusable building blocks for user interfaces. Components encapsulate both the UI and the logic associated with it. It helps us to create reusable components (small and isloated pieces of code using html, css, js). It helps us to render UI. Think about youtube's website

- Single Page Application (SPA) allows us to render as much as we need for reducing unnecessary rendering such as loading navbar, footer etc. in all the pages
- think about html tag and creating your own tag with react

2. **Virtual DOM:** React uses a virtual representation of the DOM (Document Object Model) to optimize updates. Instead of directly manipulating the actual DOM, React compares changes in the virtual DOM and efficiently updates only the necessary parts of the real DOM, reducing rendering time and improving performance.

- Load fast - Why React.js is faster? - virtual DOM compares with previous states

3. **Declarative Syntax:** React uses a declarative approach to building UIs. Developers describe what the UI should look like based on the application's state, and React takes care of updating the DOM to match that state.

4. **Unidirectional Data Flow:** React enforces a one-way data flow, which means data flows down the component hierarchy from parent components to child components. This helps maintain predictable and debuggable code.

5. **JSX (JavaScript XML):** React allows you to write UI components using JSX, which is a syntax extension for JavaScript. JSX allows you to write HTML-like code within your JavaScript files, making it easier to define UI elements.

6. **Component Lifecycle:** React components have lifecycle methods that allow developers to hook into specific points in a component's lifecycle, such as when it's mounted or updated. This is useful for performing actions like data fetching, initialization, or cleanup.

7. **State Management:** React provides a mechanism for managing component-specific state using the `useState` hook for functional components and `setState` for class components. For global state management, libraries like Redux or React Context can be used.

8. **Routing:** React can be used in combination with routing libraries like React Router to create single-page applications with client-side routing.

9. **Community and Ecosystem:** React has a large and active community, which has led to the development of a rich ecosystem of third-party libraries and tools to enhance development and improve productivity.

10. **Example of React app and competitors** - facebook, twitter, airbnb, netflix etc. competitor: Vue.js, Angular (more full-fledged / developed no need 3rd party library just like react-router-dom)

Overall, React is a powerful and popular choice for building modern web applications, and it's widely adopted by developers and organizations for its efficiency and developer-friendly approach to UI development.

#### [Environment setup](https://youtu.be/4wjI8fh77GM)

- VSCode (code editor)
- node.js (Download LTS: Long Term Support one)
(npm is included in node.js by default)
- React Developer tools extention for google, firefox, edge
- Extension: ES7 react, JS JSX snippets + “editior.snipperSuggestions”: “top”, react developer tools, material theme, setup eslint and prettier

#### [First react app](https://youtu.be/_yYO_ly9hmY?si=ruoWbevzoJrj0pqS)

#### Method 1: add React to a website with CDN

- **Code Example - 1 (create React app)**

```html







Document


.title {
background-color: brown;
color: white;
text-align: center;
}




const headingElement = React.createElement(
"h1",
{ id: "heading", className: "title" },
"Welcome to React"
);
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(headingElement);



```

- **Code Example - 2 (create React app)**

```html







Document





.title {
background-color: brown;
color: white;
text-align: center;
}




const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<h1 id="heading" className="title">
Welcome to React
</h1>
);



```

#### Method 2: create and run react app with npx

```js
// create react app command
npx create-react-app appName

// If any error occurs
npm install npm -g

// run react app command
cd appName
npm start
```

#### Method 3: create react app with bundler with vite `npm create vite@latest` swc(speedy web compiler)

#### Understand File structure

- discuss about package.json, node_modules, public, src
- [package-lock.json](https://medium.com/helpshift-engineering/package-lock-json-the-complete-guide-2ae40175ebdd#:~:text=different%20machines%2Fenvironments.-,package%2Dlock.,json%20file.) is for version control for packages. it keeps the record of node_modules tree so that when you clone and use npm i it will install exactly same versions for the packages even though their is a new versions. if you do not have package-lock.json then it will install from package.json
- keep only the index.js in src and then play with React.js
- change the title of the app inside index.html file

### [1.2 JSX and JS Expression](https://youtu.be/6-r6pBA4eUY)

**JSX: stands for JavsScript XML which allows us to use write html-like syntax inside javascript and vice versa**. react module has babbel inside of it that helps us to run jsx. JSX is similar like HTML but it is more dynamic. JSX and React are independent things and they can be used independently.

Rules for JSX

1. We can return single element using JSX, for multiple elements we can use a wrapper. We can also use Fragment here.

- why we can not return multiple elements in JSX needs to be rendered?
jsx is javascript object and we can return 2 objetcs from a function so we need to use array syntax and wrap everything inside one array

- **Code Example - 3 (render single element)**

```js
import React from "react";
import ReactDOM from "react-dom/client";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(

Anis Ecommerce website

);
```

- **React render function can render only one element**
- **Code Example - 4 (Rendering multiple elements)**

```jsx
import React from "react";
import ReactDOM from "react-dom/client";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(


Anis Express



this is sidebar


iPhone 9

iPhone 9


description: An apple mobile which is nothing like apple


Price: $549


rating: 4.69


brand: Apple


category: smartphones



iPhone X

iPhone X


description: SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...


Price: $899


rating: 4.44


brand: Apple


category: smartphones





this is a footer

```

- React.Fragment or <> > helps us to avoid div soup or unncessary div nesting
- **Code Example - 5 (Fragment)**

```js
<>
iPhone 9

iPhone 9


description: An apple mobile which is nothing like apple",


Price: $549


rating: 4.69


category: smartphones


);
<>
```

2. Remember to close all tags - ``

3. Camelcase - className

- We can use Javascript expression inside JSX
- **Code Example - 6 (JS Expression in JSX)**

```js
import React from "react";
import ReactDOM from "react-dom/client";

const imageSource1 = "https://i.dummyjson.com/data/products/1/thumbnail.jpg";
const title1 = "iPhone 9";
const description1 = "An apple mobile which is nothing like apple";
const price1 = 549;
const rating1 = 4.69;
const brand1 = "Apple";
const category1 = "smartphones";

const imageSource2 = "https://i.dummyjson.com/data/products/2/thumbnail.jpg";
const title2 = "iPhone X";
const description2 =
"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...";
const price2 = 899;
const rating2 = 4.44;
const brand2 = "Apple";
const category2 = "smartphones";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(



Anis Express



this is sidebar


iPhone 9

{title1}


description: {description1}


Price: {price1}


rating: {rating1}


brand: {brand1}


category: {category1}




iPhone 9

{title2}


description: {description2}


Price: {price2}


rating: {rating2}


brand: {brand2}


category: {category2}





this is a footer

);
```

#### [How React works under the hood](https://youtu.be/kj0cxv_dC9M)

- **Code Example - 7 (React under the hood)**

```javascript
const Message = () => {
// return

Message

;
return React.createElement("h1", {}, "welcome");
};

const Todo = () => {
return (
//
//

Check students attendance


//


// Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab, molestiae.
//


//

React.createElement(
"article",
{},
React.createElement("h2", {}, "Check students attendance"),
React.createElement(
"p",
{},
" Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab, molestiae."
)
)
);
};
```

### [1.3 Component](https://youtu.be/qgLZSNppJOU)

- **Component: A _reusable_, _nestable_ _building block_ constrcut with mainly Javascript function and HTML; CSS can be added**
- Component VS Function: Component should always start with capital letter and return JSX
- There are 2 main types of components: functional component and class component
- keep a blank line when importing your components for separting built in modules
- **Code Example - 8 (Create a reusable functional component)**

```javascript
// reusable component
import React from "react";
import ReactDOM from "react-dom/client";

const Products = () => {
const imageSource1 =
"https://i.dummyjson.com/data/products/1/thumbnail.jpg";
const title1 = "iPhone 9";
const description1 = "An apple mobile which is nothing like apple";
const price1 = 549;
const rating1 = 4.6;
const brand1 = "Apple";
const category1 = "smartphones";

const imageSource2 =
"https://i.dummyjson.com/data/products/2/thumbnail.jpg";
const title2 = "iPhone X";
const description2 =
"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...";
const price2 = 899;
const rating2 = 4.44;
const brand2 = "Apple";
const category2 = "smartphones";

return (


iPhone 9

{title1}


description: {description1}


Price: {price1}


rating: {rating1}


brand: {brand1}


category: {category1}




iPhone X

{title2}


description: {description2}


Price: {price2}


rating: {rating2}


brand: {brand2}


category: {category2}




);
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(



Anis Express




this is sidebar



this is a footer

);
```

- **Code Example - 9 (create Header, Sidebar, Footer component)**

```js
const Header = () => {
return (

Anis Express



);
};
const Sidebar = () => {
return this is sidebar;
};
const Footer = () => {
return this is a footer;
};
```

- **Code Example - 10 (App root component, Nested components)**

```js
import React from "react";
import ReactDOM from "react-dom/client";

const Products = () => {
const imageSource1 =
"https://i.dummyjson.com/data/products/1/thumbnail.jpg";
const title1 = "iPhone 9";
const description1 = "An apple mobile which is nothing like apple";
const price1 = 549;
const rating1 = 4.6;
const brand1 = "Apple";
const category1 = "smartphones";

const imageSource2 =
"https://i.dummyjson.com/data/products/2/thumbnail.jpg";
const title2 = "iPhone X";
const description2 =
"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...";
const price2 = 899;
const rating2 = 4.44;
const brand2 = "Apple";
const category2 = "smartphones";

return (


iPhone 9

{title1}


description: {description1}


Price: {price1}


rating: {rating1}


brand: {brand1}


category: {category1}




iPhone X

{title2}


description: {description2}


Price: {price2}


rating: {rating2}


brand: {brand2}


category: {category2}




);
};

const Header = () => {
return (

Anis Express



);
};
const Sidebar = () => {
return this is sidebar;
};
const Footer = () => {
return this is a footer;
};

const App = () => {
return (









);
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render();
```

- **Code Example - 11 (export, import modular component)**

- export default can be used once in a file where multiple exports can be used
- importing export default does not require {} and you can name anything on the other hand only exports requires {} and naming is strict
- export App component

```js
// App.js

import React from "react";
import ReactDOM from "react-dom/client";

const Products = () => {
const imageSource1 =
"https://i.dummyjson.com/data/products/1/thumbnail.jpg";
const title1 = "iPhone 9";
const description1 = "An apple mobile which is nothing like apple";
const price1 = 549;
const rating1 = 4.6;
const brand1 = "Apple";
const category1 = "smartphones";

const imageSource2 =
"https://i.dummyjson.com/data/products/2/thumbnail.jpg";
const title2 = "iPhone X";
const description2 =
"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...";
const price2 = 899;
const rating2 = 4.44;
const brand2 = "Apple";
const category2 = "smartphones";

return (


iPhone 9

{title1}


description: {description1}


Price: {price1}


rating: {rating1}


brand: {brand1}


category: {category1}




iPhone X

{title2}


description: {description2}


Price: {price2}


rating: {rating2}


brand: {brand2}


category: {category2}




);
};

const Header = () => {
return (

Anis Express



);
};
const Sidebar = () => {
return this is sidebar;
};
const Footer = () => {
return this is a footer;
};
const App = () => {
return (








);
};

export default App;

// import in index.js
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render();
```

- More practice for export,import
- **Code Example - 13 (More export, import)**
- separate all the components

### [1.4 Adding CSS Styling](https://youtu.be/02YWKDxLpwk)

Inline styling, CSS Stylesheet, CSS module [why you should use css module], third party packages such as Material UI, styled components

- Inline styling

```js
const headingStyle = { color: "red", fontSize: "3rem" };
sidebar goes here;
```

- CSS Stylesheet

- **Code Example - 14 (Styling component with CSS)**

```css
/*code for the App.css */
/* reset code and common starts here */
:root {
--primary-color: rgb(11, 181, 48);
--secondary-color: rgba(36, 122, 55, 0.9);
--padding: 0.5rem;
--transition: all 0.3s;
--border-radius: 0.6rem;
--box-shadow: 0.1rem 0.2rem 0.8rem rgba(205, 202, 202, 0.5);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
text-decoration: none;
list-style-type: none;
outline: none;
}
html {
scroll-behavior: smooth;
}
.flex-space-around {
display: flex;
justify-content: space-around;
align-items: center;
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
/* reset code and common ends here */

/* header starts here */
.header {
height: 10vh;
background-color: var(--primary-color);
color: white;
}
/* header ends here */

/* main starts here */
main {
height: 80vh;
}
.sidebar {
flex: 1;
padding: var(--padding);
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
align-self: flex-start;
background-color: #e6e3e3;
height: 100%;
border-right: 1px solid var(--primary-color);
}
.main-content {
flex: 3;
height: 100%;
padding: var(--padding);
overflow: scroll;
}
.products {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 2rem;
padding: 2rem 0;
}
.product__img {
width: 100%;
height: 15rem;
filter: saturate(0);
transition: var(--transition);
}
/* main ends here */

/* footer starts here */
.footer {
min-height: 10vh;
padding: var(--padding);
background-color: var(--primary-color);
color: white;
font-size: 1.1rem;
}
/* footer ends here */

/* responsiveness starts here */
@media (max-width: 992px) {
.flex-space-around,
.flex-center {
flex-direction: column;
gap: 1rem;
padding: 1rem 0;
}
.header {
min-height: 10vh;
}
.sidebar {
width: 100%;
}
.products {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}

@media (max-width: 768px) {
.products {
grid-template-columns: repeat(1, minmax(0, 1fr));
}
}
/* responsiveness ends here */
```

```js
// App.js
import React from "react";

import Header from "./components/Header";
import Sidebar from "./components/Sidebar";
import Footer from "./components/Footer";
import Products from "./components/Products";

import "./App.css";

const App = () => {
return (











);
};

export default App;

// Header.js
import React from "react";

const Header = () => {
return (

Anis Express



);
};
export default Header;

// Sidebar.js
import React from "react";

const Sidebar = () => {
return this is sidebar;
};
export default Sidebar;

// Products.js
import React from "react";

const Products = () => {
const imageSource1 =
"https://i.dummyjson.com/data/products/1/thumbnail.jpg";
const title1 = "iPhone 9";
const description1 = "An apple mobile which is nothing like apple";
const price1 = 549;
const rating1 = 4.6;
const brand1 = "Apple";
const category1 = "smartphones";

const imageSource2 =
"https://i.dummyjson.com/data/products/2/thumbnail.jpg";
const title2 = "iPhone X";
const description2 =
"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...";
const price2 = 899;
const rating2 = 4.44;
const brand2 = "Apple";
const category2 = "smartphones";

return (


iPhone 9

{title1}


description: {description1}


Price: {price1}


rating: {rating1}


brand: {brand1}


category: {category1}




iPhone X

{title2}


description: {description2}


Price: {price2}


rating: {rating2}


brand: {brand2}


category: {category2}




);
};
export default Products;

// Footer.js
import React from "react";

const Footer = () => {
return (


©Copyright by Anisul Islam




social media icons




);
};

export default Footer;
```

- CSS module: create a file name such as fileName.module.css as shown below

```css
footer {
height: 5vh;
background-color: bisque;
display: flex;
justify-content: center;
align-items: center;
}

.copyright {
font-size: 0.9rem;
}
```

- use it in from another file as shown below

```js
import React from "react";

import styles from "./footer.module.css";

const Footer = () => {
return (


All rights reserved by Anisul Islam



);
};

export default Footer;
```

### [1.5 Props and destructuring](https://youtu.be/GQx58yfYqxo)

- **props object: we can pass information from one component to another using props object. components communicate with each others via props. props is an object. props are like attributes in our HTML tag. props are readonly**
- how to pass, recieve, set default props
- how to pass JSX to component,
- **Code Example - 15 (Props sending)**

```js
import React from "react";
import Product from "./Product";

const Products = () => {
const imageSource1 = "https://i.dummyjson.com/data/products/1/thumbnail.jpg";
const title1 = "iPhone 9";
const description1 = "An apple mobile which is nothing like apple";
const price1 = 549;
const rating1 = 4.6;
const brand1 = "Apple";
const category1 = "smartphones";

const imageSource2 = "https://i.dummyjson.com/data/products/2/thumbnail.jpg";
const title2 = "iPhone X";
const description2 =
"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...";
const price2 = 899;
const rating2 = 4.44;
const brand2 = "Apple";
const category2 = "smartphones";

return (




);
};
export default Products;
```

- **Code Example - 16 (props recieveing & Destructuring)**

```js
import React from "react";

const Product = (props) => {
const { imageSource, title, description, price, rating, brand, category } =
props;
return (

iPhone 9


{title}


description: {description}


Price: {price}


rating: {rating}


brand: {brand}


category: {category}




);
};
export default Product;
```

- **Code Example - 17 (props for complex data)**

```js
// Products.js
import React from "react";
import Product from "./Product";

const Products = () => {
const products = [
{
id: 1,
title: "iPhone 9",
description: "An apple mobile which is nothing like apple",
price: 549,
discountPercentage: 12.96,
rating: 4.69,
stock: 94,
brand: "Apple",
category: "smartphones",
thumbnail: "https://i.dummyjson.com/data/products/1/thumbnail.jpg",
},
{
id: 2,
title: "iPhone X",
description:
"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...",
price: 899,
discountPercentage: 17.94,
rating: 4.44,
stock: 34,
brand: "Apple",
category: "smartphones",
thumbnail: "https://i.dummyjson.com/data/products/2/thumbnail.jpg",
},
];
return (




);
};
export default Products;
```

- create data.js in src folder and move all the todos dummy data there and import in App.js for using it.
- Can you load all the data from App.js to Products.js as props
- **Code Example - 18 (import data from another file and pass as props)**

```js
// App.js
import React from "react";

import Header from "./components/Header";
import Sidebar from "./components/Sidebar";
import Footer from "./components/Footer";
import Products from "./components/Products";
import { products } from "./data";

import "./App.css";

const App = () => {
return (











);
};

export default App;

// Products.js
import React from "react";
import Product from "./Product";

const Products = ({ products }) => {
return (




);
};
export default Products;
```

### [1.6 Mapping & rednering components](https://youtu.be/OwwmIzH7FzI)

- learn how to use map() and filter() from an array of Data.
- **Code Example - 19 (Map component with for loop)**

```js
import React from "react";
import Product from "./Product";

const Products = ({ products }) => {
const productsElement = [];
for (let index = 0; index < products.length; index++) {
productsElement.push(

);
}
return {productsElement};
};
export default Products;
```

- **Code Example - 20 (Map component with forEach higher order Array function)**

```js
import React from "react";
import Product from "./Product";

const Products = ({ products }) => {
const productsElement = [];

products.forEach((product) => {
productsElement.push(

);
});

return {productsElement};
};
export default Products;
```

- **Code Example - 21 (Map component with map higher order Array function)**

```js
import React from "react";
import Product from "./Product";

const Products = ({ products }) => {
const productsElement = products.map((product) => {
return (

);
});

return {productsElement};
};
export default Products;
```

#### [Adding unique key to each child](https://youtu.be/Dj7ynTdhy1Q)

we need to map each children of list uniquly so that react can identify them wor properly.Keys are unique. we can use same keys for JSX nodes in different arrays.

- Where I can find key?

- from database
- generate locally - crypto.randomUUID() , uuid, nanoid

- we can use index or any external package like [uuid](https://www.npmjs.com/package/uuid)
- How to use uuid:

```js
step 1: npm install uuid
step 2: import { v4 as uuidv4 } from "uuid";
step 3: uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

```

- **Code Example - 22 (Adding unique key)**

```js
// first use index
// second use the available id
// thirs use the uuid if id is not available inside the data

import React from "react";
import Product from "./Product";

const Products = ({ products }) => {
const productsElement = products.map((product) => {
return (

);
});

return {productsElement};
};
export default Products;

// get a uniqueId -> utility/getUniqueId.js
import { v4 as uuidv4 } from "uuid";
export const getUniqueId = () => uuidv4();

// Now add the unique Id in App.js
```

#### [jsx spread syntax]

- **Code Example - 23 (jsx spread syntax)**

```js
import React from "react";
import Product from "./Product";

const Products = ({ products }) => {
const productsElement = products.map((product) => {
return ;
});

return {productsElement};
};
export default Products;
```

- **Code Example - 24 (passing jsx as children)**

```js
import React from "react";

const Card = ({ children }) => {
return

{children}
;
};

export default Card;

import React from "react";
import Card from "./Card";

const Product = (props) => {
const { thumbnail, title, description, price, rating, brand, category } =
props;
return (


iPhone 9

{title}


description: {description}


Price: {price}


rating: {rating}


brand: {brand}


category: {category}




);
};
export default Product;

```

### [1.7 PropTypes](https://youtu.be/mnPJrxHUarA)

- [documentation is here](https://reactjs.org/docs/typechecking-with-proptypes.html)
- **catch bugs with typechecking.**
- We can use Typescript or Flow for checking types in the entire application for sure but PropTypes can be the first guard here for checking types.

- default props is essential when first time running without any value passing to props

```js
// lets think value can be primary or secondary one of two valyes

// checking prop types
background: PropTypes.oneOf([
'primary',
'secondary'
])
```

- **Code Example - 25 (PropTypes)**

```js
// Todos.js
import React from "react";
import PropTypes from "prop-types";

import Todo from "./Todo";

const Todos = (props) => {
const { todos } = props;

const renderTodosElement = todos.map((todo) => (

));

return {renderTodosElement};
};
Todos.defaultProps = {
todos: [],
};
Todos.propTypes = {
todos: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
title: PropTypes.string,
desc: PropTypes.string,
})
),
};

export default Todos;

// Todo.js
import React from "react";
import PropTypes from "prop-types";

const Todo = (props) => {
const { todo } = props;
return (

{todo.title}


{todo.desc}



);
};

Todo.propTypes = {
todo: PropTypes.shape({
title: PropTypes.string,
desc: PropTypes.string,
}),
};

export default Todo;

```

### [1.8 Conditional rendering](https://youtu.be/roSfZjXp5us)

- rendering components based on if-else, element variable, ternary, short circuit

- **Code Example - 26 (Conditional rendering: element variable)**

```js
// Inside App.js make adjustments
let productsElement;
if (products.length > 0) {
productsElement = ;
} else {
productsElement =

Product list is empty

;
}
return (




{productsElement}




);
```

- **Code Example - 27 (Conditional rendering: iternary)**

```js
// Inside App.js make adjustments
let productsElement =
products.length > 0 ? (

) : (

products list is empty


);

return (





{productsElement}




);

// An alternative - we can use ternary inside return () function
return (






{products.length > 0 ? (

) : (

products list is empty


)}




);
```

- **Code Example - 28 (Conditional rendering: short circuit)**

```js
// Inside App.js return() make following adjustments
return (



{products.length > 0 && }


);
```

### [Assignment 1: products-listing-app](https://github.com/anisul-Islam/react-assignment-1-products-listing-app)

### 1.9 developer tools, react and font-awesome icons

- [developer tools and extension](https://youtu.be/m1paEcDlC5U)

- [1.10 add font awesome / react icons](https://youtu.be/jHDP6myBXRM)

- [How to use react-icons](https://react-icons.github.io/react-icons/)
- **Code Example - 29 (Adding & styling react icons )**

```js
import React from "react";
import { FaFacebookF, FaYoutube, FaTwitter } from "react-icons/fa";
const Footer = () => {
return (


©Copyright by Anisul Islam









);
};

export default Footer;

// Product.js
import React from "react";
import { FaCartPlus } from "react-icons/fa";

import Card from "./Card";

const Product = (props) => {
const { thumbnail, title, description, price, rating, brand, category } =
props;
return (


iPhone 9


{title}


description: {description}


Price: {price}


rating: {rating}


brand: {brand}


category: {category}



Add To Cart




);
};
export default Product;

// App.css
/* reset code and common starts here */
:root {
--primary-color: rgb(11, 181, 48);
--secondary-color: rgba(36, 122, 55, 0.9);
--padding: 0.5rem;
--transition: all 0.3s;
--border-radius: 0.6rem;
--box-shadow: 0.1rem 0.2rem 0.8rem rgba(205, 202, 202, 0.5);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
text-decoration: none;
list-style-type: none;
outline: none;
}
html {
scroll-behavior: smooth;
}
.flex-space-around {
display: flex;
justify-content: space-around;
align-items: center;
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.card {
box-shadow: var(--box-shadow);
border-radius: var(--border-radius);
/* padding: var(--padding); */
transition: var(--transition);
}
img {
width: 100%;
height: auto;
}
.btn {
border: none;
padding: var(--padding);
border-radius: var(--border-radius);
transition: all 0.3s;
color: var(--secondary-color);
}
.btn:hover {
background-color: orange;
color: black;
}
/* reset code and common ends here */

/* header starts here */
.header {
height: 10vh;
background-color: var(--primary-color);
color: white;
}
/* header ends here */

/* main starts here */
main {
height: 80vh;
}
.sidebar {
flex: 1;
padding: var(--padding);
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
align-self: flex-start;
background-color: #e6e3e3;
height: 100%;
border-right: 1px solid var(--primary-color);
}
.main-content {
flex: 3;
height: 100%;
padding: var(--padding);
overflow: scroll;
}
.products {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 2rem;
}
.product {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.product__body {
padding: var(--padding);
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.product__img {
width: 100%;
height: 15rem;
filter: saturate(0);
transition: var(--transition);
}
/* main ends here */

/* footer starts here */
.footer {
min-height: 10vh;
padding: var(--padding);
background-color: var(--primary-color);
color: white;
font-size: 1.1rem;
}
.footer__right {
display: flex;
gap: 1rem;
}
/* footer ends here */

/* responsiveness starts here */
@media (max-width: 992px) {
.flex-space-around,
.flex-center {
flex-direction: column;
gap: 1rem;
padding: 1rem 0;
}
.header {
min-height: 10vh;
}
.sidebar {
width: 100%;
}
.products {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}

@media (max-width: 768px) {
.products {
grid-template-columns: repeat(1, minmax(0, 1fr));
}
}
/* responsiveness ends here */
```

- How to use font awesome icons directly

```js
// Add SVG Core
npm i --save @fortawesome/fontawesome-svg-core

// add Free icons styles
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/free-regular-svg-icons
npm i --save @fortawesome/free-brands-svg-icons

// add the react component
npm i --save @fortawesome/react-fontawesome@latest

// usage
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPlusCircle, faMinusCircle } from '@fortawesome/free-solid-svg-icons';
import { faYoutube } from '@fortawesome/free-brands-svg-icons';

// use className for styling icons

```

### [1.10 Adding Interactivity - event & event handler]

- Event: any user interaction like clicking button, hovering button, giving values in input field etc.
- Event handler: your response to user interactions. create a function for handling the interaction.
- state - value of anything can be changed based on your interaction and you may want to update UI based on state.
- **Code Example - 30 (event - onClick )**

```js

Add To Cart

```

- **Code Example - 31 (event Handler)**

```js
const handleClick = () => {
alert("product is added to the cart");
};

// method 1
{
alert("product is added to the cart");
}} // depends on user inetractivity as we definied the function and it is not running until we click the button
>
Add To Cart

// method 2

Add To Cart

// we can create own custom Button component
import React from "react";

const Button = (props) => {
console.log(props);

const handleClick = () => {
// we can use condition for calling multiple functions
props.onHandleAddProduct();
};

const handleAddProduct = (product) => {
alert(JSON.stringify(product, null, 4));
};

return (

{props.children}

);
};

export default Button;

// more simplified
import React from "react";

const Button = (props) => {
return (

{props.children}

);
};

export default Button;
```

- **Code Example - 32 (Pass parameter with event )**

```js
const handleAddProduct = (e, product) => {
e.stopPropagation();
console.log("Product Event: ", e);
alert(JSON.stringify(product, null, 4));
};

{
handleAddProduct(e, product);
}}
>
Add To Cart
;
```

- **Code Example - 33 (onChange Event )**

```js
import React from "react";

const NewProduct = () => {
const handleChange = (event) => {
console.log(event.target.value);
};
return (


Create Product


Title:


Price:



);
};

export default NewProduct;
```

- **Code Example - 34 (More complex example of onChange Event )**

```js
import React from "react";

const NewProduct = () => {
const inputs = [
{
id: 1,
type: "text",
name: "title",
placeholder: "Enter product title",
required: true,
},
{
id: 2,
type: "number",
name: "price",
placeholder: "Enter product price",
required: true,
},
];
const handleChange = (event) => {
console.log(event.target.value);
};

return (


Create Product



);
};

// More simplified
const NewProduct = () => {
const inputs = [
{
id: 1,
type: "text",
name: "title",
placeholder: "Enter product title",
required: true,
},
{
id: 2,
type: "number",
name: "price",
placeholder: "Enter product price",
required: true,
},
];
const handleChange = (event) => {
console.log(event.target.value);
};

const renderInputs = inputs.map((input) => {
return (

);
});

return (


Create Product


{renderInputs}

);
};

// more simplified
;

// Input.js
import React from "react";
const Input = (props) => {
const { onChange, ...inputProps } = props; // getting onChnage from props and putting rest of the things inside inputProps

console.log([inputProps]);
return (

);
};

export default Input;
```

- **Code Example - 35 (Event Bubbling - child event can effect parent event )**

```js
const handleAddProduct = (e, product) => {
e.stopPropagation();
console.log("Product Event: ", e);
alert(JSON.stringify(product, null, 4));
};
```

- **Code Example - 36 (onSubmit Event )**

### [1.11 useState Hooks](https://youtu.be/skUOiqcVurY)

- without state management

```js
const Counter = () => {
let count = 0;

const handleIncrement = () => {
count++;
alert(count);
};
const handleDecrement = () => {
count--;
alert(count);
};
const handleReset = () => {
count = 0;
alert(count);
};

return (


Count: {count}


+
0
-

);
};

export default Counter;
```

- state is a memory for component where we can update value and re-render the component
- state is a global variable thats why when you even re-render it fetch the last updated value
- hooks are function which we can implement in our component - useState, useEffect
- useState() hook helps us to track state in a functional component.
- **Code Example - 36 (Counter App )**

```js
// App.js
import React from "react";

import Counter from "./components/Counter";

const App = () => {
return (




);
};

export default App;
```

```js
// Counter.js
import React, { useState } from "react";

function Counter() {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1); // setCount (count => count + 1)
};

return (


Counter: {count}


+

);
}

export default Counter;
```

- we can also use name attribute for identifying element and use 1 function instead of many. from ebent handler we can use event.target.name and then decide what to do or not? - [1 handler for multiple elements] (https://github.com/anisul-Islam/react-counter-app-1-function/blob/master/src/components/Counter.js)

- **Code Example - 37 (store data in state )**

```js
import React, { useState } from "react";
import { FaCartPlus } from "react-icons/fa";
import Button from "./Button";

import Card from "./Card";

const Product = (props) => {
const { thumbnail, title, description, price, rating, brand, category } =
props;
const product = props;
const [cartProducts, setCartProducts] = useState([]);
const handleAddProduct = (e, product) => {
e.stopPropagation();
setCartProducts((prevState) => {
return [...prevState, product];
});
};
console.log(cartProducts);
return (


iPhone 9


{title}


description: {description}


Price: {price}


rating: {rating}


brand: {brand}


category: {category}


{/*
Add To Cart
*/}
{
handleAddProduct(e, product);
}}
>
Add To Cart




);
};
export default Product;
```

- **Code Example - 38 (why update data based on prevState?)**

- update state based on prev value - `setCount (count => count + 1)`

```js
const handleIncrement = (e) => {
e.stopPropagation();

setcount(count + 1);
setcount(count + 1);
setcount(count + 1);

console.log("increment count: ", count);
};

const handleIncrement = (e) => {
e.stopPropagation();

setcount((count) => count + 1);
setcount((count) => count + 1);
setcount((count) => count + 1);

console.log("increment count: ", count);
};

const handleIncrement = (e) => {
e.stopPropagation();
setTimeout(() => {

setcount((count) => count + 1);
}, 3000);
console.log("increment count: ", count);
};
```

### [Assignment - 2: Counter App](https://github.com/anisul-Islam/react-assignment-2-counter-app)

### [1.12 Forms and Controlled components](https://youtu.be/kvGNlTh3rNQ)

- create a new resouce such as NewProduct, NewUser, NewTodo etc.
- **Code Example - 39 (get data from a form)**

```js

```

- [How to create forms in react using react-hook-form](https://www.freecodecamp.org/news/how-to-create-forms-in-react-using-react-hook-form/)

#### [upating object in state](https://beta.reactjs.org/learn/updating-objects-in-state)

- **Code Example - 40 (updating object in state)**

```js
import React, { useState } from "react";

const NewUser = () => {
const [user, setUser] = useState({
name: "",
email: "",
password: "",
});
const handleChange = (event) => {
event.stopPropagation();
setUser((prevUser) => {
return { ...prevUser, [event.target.name]: event.target.value };
});
};

const handleSubmit = (event) => {
event.preventDefault();
console.log("submitted");
alert(JSON.stringify(user));
};

return (




name:



email:



password:


Add User


);
};

export default NewUser;
```

- **Code Example - 41 (updating nested object in state)**

```js

```

#### [Upating array in state](https://beta.reactjs.org/learn/updating-arrays-in-state)

- **Code Example - 42 (updating array in state)**

```js

```

#### [Form Validation without library](https://github.com/anisul-Islam/form-validation-without-library)

### [1.13 data passing: child to parent component, state lifting](https://youtu.be/xdW2uFA-SOg)

- Another practical example: https://youtu.be/h7yq5lfDZc8
- [Freecodecamp doc](https://www.freecodecamp.org/news/what-is-lifting-state-up-in-react/)
- **Code Example - 43 (state lifting)**

```js
// App.js
step 1: create a callback function that will help us to get the data from child component
const handleAddNewTodo = (newTodo) => {
console.log(newTodo);
};

step 2: pass the function as props to child to component

step 3: receive the function props and use it for passing the data from child to parent
// AddTodo.js
import PropTypes from "prop-types";

const handleSubmit = (event) => {
event.preventDefault();
const newTodo = { id: getUniqueId(), title, desc };
setTitle("");
setDesc("");
props.onHandleAddNewTodo(newTodo);
};

AddTodo.propTypes = {
onHandleAddNewTodo: PropTypes.func,
};

// Another Example
function App() {
const [users, setUsers] = useState([
{ name: 'alex', email: 'alex@gmail.com' },
]);

console.log(users);

return (




)
}

const Test = (props) => {
const { setUsers } = props;

const [user, setUser] = useState({ name: '', email: '' });
const handleSubmit = (event) => {
event.preventDefault();
setUsers((users) => [...users, user]);
setUser({
name: '',
email: '',
});
};
const handleChange = (event) => {
const name = event.target.name;
setUser({ ...user, [name]: event.target.value });
};
}
```

- **Code Example - 44 (state lifting and delete item)**

```js
// App.js
step 1: create a function that will help us to get the id from child component Todo.js
const handleDeleteTodo = (id) => {
console.log(id);
};

step 2: pass the function as props to App.js -> Todos.js -> Todo.js

step 3: After passing the function from App.js to Todo.js now lets handle the button click and get the id so that we pass the id to App.js with the help of the function onHandleDeleteTodo
// Todo.js

const { todo, onHandleDeleteTodo } = props;

const handleDelete = (id) => {
onHandleDeleteTodo(id);
};

{
handleDelete(todo.id);
}}
>

step 4: finally with the help of the id lets delete the item from todos state inside App.js

const handleDeleteTodo = (id) => {
setTodos(todos.filter((todo) => todo.id !== id));
};
```

### [1.14 useRef hook - Uncontrolled component](https://youtu.be/l5z137GWakU)

- If we look at the AddTodo component then you will see we are not using those title and desc state inside the component that much so we can avoid state and make the component stateless
- **Code Example - 45 (useRef hook for getting form value)**

```js
import React, { useRef } from "react";
import PropTypes from "prop-types";

import { getUniqueId } from "../utility/getUniqueId";

const AddTodo = (props) => {
const titleRef = useRef("");
const descRef = useRef("");

const handleSubmit = (event) => {
event.preventDefault();
const title = titleRef.current.value;
const desc = descRef.current.value;
const newTodo = { id: getUniqueId(), title, desc };
props.onHandleAddNewTodo(newTodo);
titleRef.current.value = "";
descRef.current.value = "";
};

return (



Add New Todo



Todo Title:



Todo description:




Add Todo




);
};

AddTodo.propTypes = {
onHandleAddNewTodo: PropTypes.func,
};

export default AddTodo;
```

### [1.15 dynamic styling in React](https://youtu.be/Eru9-kZfhw4)

- Now lets add some coditional styling
- **Code Example - 46 (conditional styling)**

```js
import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";

import { getUniqueId } from "../utility/getUniqueId";

const AddTodo = (props) => {
const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");

const [isTitleValid, setIsTitleValid] = useState(false);
const [isDescValid, setIsDescValid] = useState(false);

useEffect(() => {
if (title.trim().length > 3) {
setIsTitleValid(true);
}
if (desc.trim().length > 9) {
setIsDescValid(true);
}
}, [title, desc]);

const handleTitleChange = (event) => {
setTitle(event.target.value);
};

const handleDescriptionChange = (event) => {
setDesc(event.target.value);
};

const handleSubmit = (event) => {
event.preventDefault();

const newTodo = { id: getUniqueId(), title, desc };
props.onHandleAddNewTodo(newTodo);
setTitle("");
setDesc("");
};

return (



{JSON.stringify({ id: getUniqueId(), title, desc }, undefined, 2)}


Add New Todo



Todo Title:

{!isTitleValid &&

Title Should be at least 4 characters

}


Todo description:

{!isDescValid && (

Description Should be at least 10 characters


)}



Add Todo




);
};

AddTodo.propTypes = {
onHandleAddNewTodo: PropTypes.func,
};

export default AddTodo;
```

### [Assignment - 3: Add New Product](https://github.com/anisul-Islam/react-assignment-3-add-new-product)

### [1.16 class component](https://youtu.be/fu76idgpuEI)

### [1.17 state, setState, event handler](https://youtu.be/9AtJ4dM2xOU)

- state is a js object for storing current situation of a component

- **Code Example - 47 (Counter App using class component)**

```js
// App.js
import React from "react";

import Counter from "./components/Counter";

const App = () => {
return (




);
};

export default App;
```

```js
// Counter.js
import React, { Component } from "react";

export default class Counter extends Component {
constructor(props) {
super(props);

this.state = {
count: 0,
};
}

handleIncrement = () => {
this.setState({
count: this.state.count + 1,
});
};

render() {
return (


Counter: {this.state.count}


+

);
}
}
```

### [1.18 react todo projects]

- [react todo project](https://github.com/anisul-Islam/react-todo-project)

## 2. Intermediate React.js Topics

### [2.1 life cycle methods of a class component](https://youtu.be/Yz5qTOmSt0M)

- **Code Example - 48 (life cycle methods of a class component)**

```js
// Counter App
import React, { Component } from "react";

class Counter extends Component {
constructor(props) {
super(props);

this.state = {
count: 0,
};
}

handleIncrement = () => {
this.setState({
count: this.state.count + 1,
});
};

render() {
return (


Count: {this.state.count}


Increment

);
}
}
export default Counter;

// LifeCycle Methods
import React, { Component } from 'react';
// mounting - constructor -> render -> componentDidMount() (it will be called once, API Call is recommended here)
// updating - state/props -> shouldComponentUpdate()-> render -> componentDidUpdate ->
// unmounting -> componentDidUnmount()
class LifeCycle extends Component {
constructor(props) {
super(props);
console.log('constructor');
this.state = {
count: 0
};
}

handleIncrement = () => {
this.setState({
count: this.state.count + 1
});
};
componentDidMount() {
console.log('componentDidMount');
}
componentDidUpdate() {
console.log('componentDidUpdate');
}
shouldComponentUpdate() {
console.log('shouldComponentUpdate()');
return true;
}

render() {
console.log('render');
return (


Count: {this.state.count}


Increment

);
}
}
export default LifeCycle;

```

### [2.2 useEffect Hook](https://youtu.be/XEU3jlV9syI)

The `useEffect` hook in React allows you to perform side effects in your functional components. Side effects can include data fetching, DOM manipulation, setting up subscriptions, and more. It's a crucial hook for managing the lifecycle of your components.

Rule: Don’t call Hooks inside loops, conditions, or nested functions

useEffct = componentDidMount + componentDidUpdate + componentWillUnmount

Here's how to use the `useEffect` hook in a React component:

```javascript
import React, { useState, useEffect } from 'react';

function ExampleComponent() {
// State and other code here

useEffect(() => {
// This function will run after the component renders

// Place your side effect code here
console.log('Component has rendered');

// If needed, you can return a cleanup function
return () => {
// This code will run before the component unmounts
console.log('Component will unmount');
};
}, []); // Dependency array (optional)

return (
// JSX to render
);
}

export default ExampleComponent;
```

Key points about the `useEffect` hook:

1. The `useEffect` hook takes two arguments:

- The first argument is a function that contains your side effect code.
- The second argument is an array of dependencies. If any of these dependencies change, the side effect function will be re-executed. If you want the side effect to run only once (similar to `componentDidMount` in class components), you can pass an empty array (`[]`) as the second argument.

2. The side effect function is run after the component has rendered. It can run multiple times if the dependencies change (if provided in the dependency array).

3. You can return a cleanup function from the side effect function. This cleanup function will run before the component unmounts. It's useful for unsubscribing from subscriptions, canceling network requests, or any cleanup work.

Here's a breakdown of how you might use the `useEffect` hook for common scenarios:

- **Data Fetching**: Fetch data when the component mounts, and clean up any resources when it unmounts.

```javascript
useEffect(() => {
const fetchData = async () => {
// Fetch data here
};

fetchData();

return () => {
// Cleanup resources (e.g., cancel network request)
};
}, []);
```

- **Updating the Title**: Change the document title when the component mounts.

```javascript
useEffect(() => {
document.title = "New Page Title";

return () => {
document.title = "Previous Page Title";
};
}, []);
```

- **Listening for State Changes**: Execute code when specific state values change.

```javascript
useEffect(() => {
// Execute code when someStateValue changes
}, [someStateValue]);
```

- **Subscription Management**: Subscribe to a service and unsubscribe when the component unmounts.

```javascript
useEffect(() => {
const subscription = service.subscribe((data) => {
// Handle data
});

return () => {
subscription.unsubscribe();
};
}, []);
```

The `useEffect` hook is a versatile tool for managing side effects in your React components and can help you keep your code clean and efficient.

- **Code Example - 49 (useEffect hook)**

```js
import React, { useEffect, useState } from "react";

const UseEffectHook = () => {
const [count, setCount] = useState(0);

// useEffect(() => {
// //Runs on every render
// });

// useEffect(() => {
// //Runs only on the first render
// }, []);

// useEffect(() => {
// //Runs on the first render
// //And any time any dependency value changes
// }, [prop, state]);

//Runs on every render
// useEffect(() => {
// console.log("useEffect: " + count);
// });

//Runs only on the first render
// useEffect(() => {
// console.log(count);
// }, []);

//Runs on the first render and also when the dependecy value changes
useEffect(() => {
console.log(count);
}, [count]);

return (


Count: {count}


{
setCount((count) => count + 1);
}}
>
+


);
};

export default UseEffectHook;
```

```js
// Another example
import React, { useState, useEffect } from "react";

const UseEffectExample = () => {
const [count, setCount] = useState(0);
const [greeting, setGreeting] = useState("good morning");
useEffect(() => {
console.log("hello from useeffect");
}, [count]);

return (


Count: {count}


{
setCount((count) => count + 1);
}}
>
+

{
setGreeting(greeting + "2");
}}
>
greeting

{greeting}



);
};

export default UseEffectExample;
```

#### [fatch data using useEffect Hook](https://youtu.be/Z-EkslDJTJI)

- **Code Example - 50 (fetch data using useEffect hook)**

```js
import React, { useEffect, useState } from "react";

import "./App.css";

const App = () => {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

useEffect(() => {
setIsLoading(true);
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => {
if (!res.ok) {
throw new Error("could not fetch the data");
}
return res.json();
})
.then((result) => {
setUsers(result);
setIsLoading(false);
})
.catch((error) => {
setIsLoading(false);
setError(error.message);
});
}, []);
console.log(users);
const renderUsers = users.map((user) => {
const { id, name, username, email, phone, website } = user;
return (

{id}


{name}


{username}


{email}


{phone}


{website}



);
});

return (


{isLoading &&

Loading...

}
{error ?

{error}

: {renderUsers}}

);
};

export default App;
```

- **Code Example - 51 (fetch data using useEffect hook - async await)**

```js
import React, { useEffect, useState } from "react";

import "./App.css";

const App = () => {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

const fetchUsers = async () => {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
if (!response.ok) {
throw new Error(`Request failed with status: ${response.status}`);
}
const result = await response.json();
setUsers(result);
setIsLoading(false);
} catch (error) {
setIsLoading(false);
setError(error.message);
}
};

useEffect(() => {
setIsLoading(true);
fetchUsers();
}, []);

const renderUsers = users.map((user) => {
const { id, name, username, email, phone, website } = user;
return (

{id}


{name}


{username}


{email}


{phone}


{website}



);
});

return (


{isLoading &&

Loading...

}
{error ?

{error}

: {renderUsers}}

);
};

export default App;
```

#### [How to create custom hook](https://youtu.be/ZWschU7H_20)

- **Code Example - 52 (custom hook)**

```js
import React, { useState, useEffect } from "react";

const useFetch = (URL) => {
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

const fetchUsers = async () => {
try {
const response = await fetch(URL);
const result = await response.json();
setData(result);
setIsLoading(false);
} catch (error) {
setIsLoading(false);
setError(error.message);
}
};

useEffect(() => {
setIsLoading(true);
fetchUsers();
}, []);

return { data, isLoading, error };
};

export default useFetch;
```

#### [Create services for making http requests]

- **Code Example - 53 (services for http requests)**

```js
// UserService.js
import axios from "axios";

const BASE_URL = "https://jsonplaceholder.typicode.com";

// using axios
export const getAllUsers = async () => {
const response = await axios.get(`${BASE_URL}/users/202`);
return response.data;
};

// using fetch
export const createUser = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify({
title: "foo",
body: "bar",
userId: 1,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
});
return response;
};

// App.js
import React, { useEffect, useState } from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import "./App.css";
import { getAllUsers } from "./services/UserService";

const App = () => {
const [users, setUsers] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);

const fetchUsers = async () => {
try {
const result = await getAllUsers();
console.log(result);
setUsers(result);
setIsLoading(false);
} catch (err) {
setIsLoading(false);
setError(err.message);
toast(err.message);
}
};

useEffect(() => {
setIsLoading(true);
fetchUsers();
}, []);

const renderUsers = users.map((user) => {
const { id, name, username, email, phone, website } = user;
return (

{id}


{name}


{username}


{email}


{phone}


{website}



);
});

return (



{isLoading &&

Loading...

}
{error ?

{error}

: {renderUsers}}

);
};

export default App;
```

### [Assignment 4 - fetch products](https://github.com/anisul-Islam/react-assignment-4-fetch-products)

### [2.3 useReducer hook](https://youtu.be/l_BhBNhNwhE)

- useState and useReducers helps us to manage states
- useReducer is a good choice if you have multiple & complex states (objects, arrays)
- useReducer is powerful when managing complex logic for updating the states
- useState is better if you are using state for simple purpose and handling string, boolean or number type.
- **Code Example - 54 (without useReducer)**

```js
// without useReducer
import React, { useState } from "react";

// books, modalText, isModalOpen
// add book - modalText
// remove book - modalText
const dummyBooks = [
{ id: 1, title: "book1" },
{ id: 2, title: "book2" },
];
const Modal = ({ modalText }) => {
return

{modalText}

;
};
const App = () => {
// every time update 3 relevant states
const [books, setBooks] = useState(dummyBooks);
const [modalText, setModalText] = useState("");
const [isModalOpen, setIsModalOpen] = useState(false);

const [bookTitle, setBookTitle] = useState("");

const handleAddBook = (event) => {
event.stopPropagation();
setBookTitle(event.target.value);
};
const handleDeleteBook = (event, id) => {
event.stopPropagation();
const filterBooks = books.filter((book) => book.id !== id);
setBooks(filterBooks);
setIsModalOpen(true);
setModalText(" book is deleted");
};

const handleSubmit = (event) => {
event.preventDefault();
const newBook = { id: new Date().getTime().toString(), title: bookTitle };
setBooks((prevBooks) => {
return [...prevBooks, newBook];
});
setIsModalOpen(true);
setModalText("New book is added");
};

return (




Add Book

{isModalOpen && }


{books.map((book) => {
const { id, title } = book;
return (

id: {id}


title: {title}


{
handleDeleteBook(event, id);
}}
>
Delete


);
})}


);
};

export default App;
```

- **Code Example - 55 (with useReducer)**

```js
import React, { useState, useReducer } from "react";

// books, modalText, isModalOpen
// add book - modalText
// remove book - modalText
const dummyBooks = [
{ id: 1, title: "book1" },
{ id: 2, title: "book2" },
];
const Modal = ({ modalText }) => {
return

{modalText}

;
};

// based on action type reducer will update the state & return the state
const reducer = (state, action) => {
// action object has action.type and action.payload
switch (action.type) {
case "ADD":
const allBooks = [...state.books, action.payload];
return {
...state,
books: allBooks,
isModalOpen: true,
modalText: "new book is added",
};
case "DELETE":
const filteredBooks = state.books.filter(
(book) => book.id !== action.payload
);
return {
...state,
books: filteredBooks,
isModalOpen: true,
modalText: "book is deleted",
};

default:
return state;
}
};

const initialState = {
books: dummyBooks,
isModalOpen: false,
modalText: "",
};

const App = () => {
// const [books, setBooks] = useState(dummyBooks);
// const [modalText, setModalText] = useState('');
// const [isModalOpen, setIsModalOpen] = useState(false);

const [bookState, dispatch] = useReducer(reducer, initialState);

const [bookTitle, setBookTitle] = useState("");

const handleTitleChange = (event) => {
event.stopPropagation();
setBookTitle(event.target.value);
};
const handleDeleteBook = (event, id) => {
event.stopPropagation();
dispatch({ type: "DELETE", payload: id });
};

const handleSubmit = (event) => {
event.preventDefault();
const newBook = { id: new Date().getTime().toString(), title: bookTitle };
dispatch({ type: "ADD", payload: newBook });
setBookTitle("");
};

return (




Add Book

{bookState.isModalOpen && }


{bookState.books.map((book) => {
const { id, title } = book;
return (

id: {id}


title: {title}


{
handleDeleteBook(event, id);
}}
>
Delete


);
})}


);
};

export default App;
```

### [2.4 Routing](https://youtu.be/1_powatXjds)

- [react-routing-project](https://github.com/anisul-Islam/react-routing-project)
- react-router
- **Code Example - 56 (basic routing)**

```js
// create few pages -> Home.js, About.js, Contact.js, Error.js
import React from "react";
import { BrowserRouter, Link, Route, Routes } from "react-router-dom";

import About from "./pages/About";
import Contact from "./pages/Contact";
import Home from "./pages/Home";
import Error from "./pages/Error";
const App = () => {
return (




} />
} />
} />
} />



);
};

export default App;
```

#### [Navigation and redirect](https://youtu.be/DooqgS1JDg0)

- **Code Example - 57 (basic routing with Navbar)**

```js
import React from "react";
import { BrowserRouter, Link, Route, Routes } from "react-router-dom";

import About from "./pages/About";
import Contact from "./pages/Contact";
import Home from "./pages/Home";
import Error from "./pages/Error";

const App = () => {
return (





Home


About


Contact



} />
} />
} />
} />



);
};

export default App;

// create a separate Navbar.js component inside layout folder

// Active Link
import React from 'react';
import { NavLink } from 'react-router-dom';

const Navbar = () => {
return (


Home


About


Contact


);
};

export default Navbar;
.active {
color: orange;
}
```

- **Code Example - 58 (navigate with useNavigate)**

```js
import React from "react";
import { useNavigate } from "react-router-dom";

const Error = () => {
const navigate = useNavigate();

return (


Error Page


{
navigate("/");
}}
>
Go to Home Page


);
};

export default Error;
```

#### [Dynamic routing using useParams](https://youtu.be/g5B0Vq3jHbA)

- **Code Example - 59 (dynamic routing)**
- based on the parameters show dynamic data in a page
- step 1: create some dummy data

```js
export const blogsData = [
{
id: 1,
title: "html",
body: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe doloremque impedit cumque aperiam dignissimos cum eveniet reiciendis iste asperiores voluptates repudiandae et, deserunt nobis commodi hic! Ratione accusamus assumenda alias rerum, esse et aperiam nihil sunt amet nobis quod libero sapiente! Harum reiciendis quos tempora blanditiis recusandae impedit iusto ipsum?",
},
{
id: 2,
title: "css",
body: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe doloremque impedit cumque aperiam dignissimos cum eveniet reiciendis iste asperiores voluptates repudiandae et, deserunt nobis commodi hic! Ratione accusamus assumenda alias rerum, esse et aperiam nihil sunt amet nobis quod libero sapiente! Harum reiciendis quos tempora blanditiis recusandae impedit iusto ipsum?",
},
{
id: 3,
title: "js",
body: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe doloremque impedit cumque aperiam dignissimos cum eveniet reiciendis iste asperiores voluptates repudiandae et, deserunt nobis commodi hic! Ratione accusamus assumenda alias rerum, esse et aperiam nihil sunt amet nobis quod libero sapiente! Harum reiciendis quos tempora blanditiis recusandae impedit iusto ipsum?",
},
{
id: 4,
title: "react.js",
body: "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe doloremque impedit cumque aperiam dignissimos cum eveniet reiciendis iste asperiores voluptates repudiandae et, deserunt nobis commodi hic! Ratione accusamus assumenda alias rerum, esse et aperiam nihil sunt amet nobis quod libero sapiente! Harum reiciendis quos tempora blanditiis recusandae impedit iusto ipsum?",
},
];
```

- step 2: load and map the data in Blogs.js page

```js
import React, { useState } from "react";
import { Link } from "react-router-dom";

import { blogsData } from "../data";
const Blogs = () => {
const [blogs, setBlogs] = useState(blogsData);

const truncateString = (str, number) => {
if (str.length > number) {
return str.slice(0, number) + "...";
} else return str;
};

const renderBlogsElement = blogs.map((blog) => {
return (

{blog.title}


{truncateString(blog.body, 100)}



Learn More