├── .templates ├── react-constant │ ├── constant.js │ ├── hooks.jsx │ └── index.jsx └── react-basic │ ├── hooks.jsx │ └── index.jsx ├── prototype.js ├── 11.jpg ├── 12.jpg ├── 13.jpg ├── 14.jpg ├── 15.jpg ├── 16.jpg ├── 17.jpg ├── 18.jpg ├── 19.jpg ├── 110.jpg ├── 112.jpg ├── 113.jpg ├── 115.jpg ├── 116.jpg ├── 117.jpg ├── 118.jpg ├── React-Tutorials-main ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── src │ ├── App.js │ ├── setupTests.js │ ├── components │ │ ├── ErrorBoundaries │ │ │ ├── ErrorDemo.js │ │ │ ├── CounterDemo.js │ │ │ └── ErrorBoundaries.js │ │ ├── Ref │ │ │ ├── ChildRef.js │ │ │ ├── ParentRef.js │ │ │ └── RefDemo.js │ │ ├── Fragments │ │ │ ├── Columns.js │ │ │ ├── TableDemo.js │ │ │ ├── FragmentDemo.js │ │ │ └── ListDemo.js │ │ ├── Event Handling │ │ │ ├── ChildofClassComponent.js │ │ │ ├── FunctionalComponent.js │ │ │ └── ClassComponent.js │ │ ├── Portals │ │ │ ├── ChildComponent.js │ │ │ └── ParentComponent.js │ │ ├── HOC │ │ │ ├── CommentsCount.js │ │ │ ├── LikesCount.js │ │ │ └── HOC.js │ │ ├── Props │ │ │ ├── Cars.js │ │ │ └── CarDetails.js │ │ ├── PureComponent │ │ │ ├── NormalComponent.js │ │ │ └── PureComponents.js │ │ ├── Lifecycle Methods │ │ │ ├── DisplayClock.js │ │ │ └── Clock.js │ │ ├── Conditional Rendering │ │ │ └── ConditionalRendering.js │ │ ├── Forms │ │ │ └── DemoForm.js │ │ └── API │ │ │ └── FetchApi.js │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── App.css │ ├── logo.svg │ └── serviceWorker.js ├── .gitignore ├── package.json └── README.md ├── README.md ├── dvh lvh svh in css.png ├── Javascript ├── scrollTop.js ├── randomRender.js ├── sort.js ├── bgHalf.css ├── IIFE.JS ├── first-class entity.js ├── data-destructuring.js ├── Currying_ChainClosure.js ├── null vs undefined.js ├── closure.js ├── for.js ├── prevState.js ├── HOF.js ├── msgChatScrollBottom.jsx ├── value_refrence_type.js ├── filter.js ├── callback.js ├── callStack.js ├── object.keys.js ├── outside.js ├── var const let.js ├── classes.js ├── reduce.js ├── promis.js ├── this.js ├── callBackOther.js ├── jsMethods.js └── checkBoxburgerIcon.html ├── javascript_interview_bank-main.zip ├── Interview questions [candidate edition].pdf ├── Novoresume - Your guide to Getting Hired in 2022.pdf ├── Screenshot_2023-07-05-08-35-10-902_com.linkedin.android.jpg ├── Screenshot_2023-07-05-10-43-19-982_com.linkedin.android.jpg ├── Screenshot_2023-07-05-10-44-20-226_com.linkedin.android.jpg ├── Screenshot_2023-07-05-10-46-43-516_com.linkedin.android.jpg ├── persian-articles-website.txt ├── reactQuery-keys.ts ├── React js ├── ForwardingRef.jsx ├── Ref.jsx ├── LifeCycle.jsx ├── Responsive.css ├── Portals.jsx ├── Error Boundary.jsx ├── useMemo useCallback.js ├── Responsive.jsx ├── React-Lazy.jsx ├── useDebounce.jsx └── Controlled Uncontrolled Components.jsx ├── font-preload.js ├── remove_duplicates.js ├── iphone zoom disable.css ├── local-fonts.js ├── nextjs-tips.txt ├── debounceFn.js ├── testing.js ├── useDebounce.jsx ├── useGeoLocation.tsx ├── re-render.isx ├── useDebounce-typescript.tsx ├── template.config.js ├── bind_call_apply.js ├── testing-persian.js ├── utils.ts ├── mock api vs real api.txt └── task-doc.md /.templates/react-constant/constant.js: -------------------------------------------------------------------------------- 1 | const test = "test"; 2 | -------------------------------------------------------------------------------- /prototype.js: -------------------------------------------------------------------------------- 1 | https://ditty.ir/courses/javascript/prototypes/nYLA5 2 | -------------------------------------------------------------------------------- /11.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/11.jpg -------------------------------------------------------------------------------- /12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/12.jpg -------------------------------------------------------------------------------- /13.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/13.jpg -------------------------------------------------------------------------------- /14.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/14.jpg -------------------------------------------------------------------------------- /15.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/15.jpg -------------------------------------------------------------------------------- /16.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/16.jpg -------------------------------------------------------------------------------- /17.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/17.jpg -------------------------------------------------------------------------------- /18.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/18.jpg -------------------------------------------------------------------------------- /19.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/19.jpg -------------------------------------------------------------------------------- /110.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/110.jpg -------------------------------------------------------------------------------- /112.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/112.jpg -------------------------------------------------------------------------------- /113.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/113.jpg -------------------------------------------------------------------------------- /115.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/115.jpg -------------------------------------------------------------------------------- /116.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/116.jpg -------------------------------------------------------------------------------- /117.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/117.jpg -------------------------------------------------------------------------------- /118.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/118.jpg -------------------------------------------------------------------------------- /React-Tutorials-main/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-javascript-interview-codes 2 | 3 | js interview codes
4 | 5 | react interview codes 6 | 7 | -------------------------------------------------------------------------------- /dvh lvh svh in css.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/dvh lvh svh in css.png -------------------------------------------------------------------------------- /Javascript/scrollTop.js: -------------------------------------------------------------------------------- 1 | function scrollTop() { 2 | window.scrollTo({ 3 | top: 0, 4 | behavior: "smooth", 5 | }); 6 | } 7 | -------------------------------------------------------------------------------- /javascript_interview_bank-main.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/javascript_interview_bank-main.zip -------------------------------------------------------------------------------- /Javascript/randomRender.js: -------------------------------------------------------------------------------- 1 | const num = [6, 3, 5, 9, 1]; 2 | 3 | const random = num.sort((a, b) => Math.random() - 0.5); 4 | 5 | console.log(random); 6 | -------------------------------------------------------------------------------- /React-Tutorials-main/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/React-Tutorials-main/public/favicon.ico -------------------------------------------------------------------------------- /React-Tutorials-main/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/React-Tutorials-main/public/logo192.png -------------------------------------------------------------------------------- /React-Tutorials-main/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/React-Tutorials-main/public/logo512.png -------------------------------------------------------------------------------- /Interview questions [candidate edition].pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/Interview questions [candidate edition].pdf -------------------------------------------------------------------------------- /Javascript/sort.js: -------------------------------------------------------------------------------- 1 | // sort method 2 | const number = [1, 6, 2, 4, 9, 7, 5]; 3 | const sorted = number.sort((a, b) => { 4 | return a - b; 5 | }); 6 | console.log("sorted :", sorted); 7 | -------------------------------------------------------------------------------- /Novoresume - Your guide to Getting Hired in 2022.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/Novoresume - Your guide to Getting Hired in 2022.pdf -------------------------------------------------------------------------------- /Screenshot_2023-07-05-08-35-10-902_com.linkedin.android.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/Screenshot_2023-07-05-08-35-10-902_com.linkedin.android.jpg -------------------------------------------------------------------------------- /Screenshot_2023-07-05-10-43-19-982_com.linkedin.android.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/Screenshot_2023-07-05-10-43-19-982_com.linkedin.android.jpg -------------------------------------------------------------------------------- /Screenshot_2023-07-05-10-44-20-226_com.linkedin.android.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/Screenshot_2023-07-05-10-44-20-226_com.linkedin.android.jpg -------------------------------------------------------------------------------- /Screenshot_2023-07-05-10-46-43-516_com.linkedin.android.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/EsrafilElahi/react-javascript-interview-codes/HEAD/Screenshot_2023-07-05-10-46-43-516_com.linkedin.android.jpg -------------------------------------------------------------------------------- /Javascript/bgHalf.css: -------------------------------------------------------------------------------- 1 | body { 2 | width: 100%; 3 | height: 100vh; 4 | background: linear-gradient( 5 | to right, 6 | pink 0%, 7 | pink 50%, 8 | aqua 50%, 9 | aqua 100% 10 | ) 11 | } -------------------------------------------------------------------------------- /.templates/react-basic/hooks.jsx: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from 'react'; 2 | 3 | function use__templateNameToPascalCase__() { 4 | 5 | return {} 6 | } 7 | 8 | export default use__templateNameToPascalCase__; 9 | -------------------------------------------------------------------------------- /.templates/react-constant/hooks.jsx: -------------------------------------------------------------------------------- 1 | import { useState, useEffect } from 'react'; 2 | 3 | function use__templateNameToPascalCase__() { 4 | 5 | return {} 6 | } 7 | 8 | export default use__templateNameToPascalCase__; 9 | -------------------------------------------------------------------------------- /Javascript/IIFE.JS: -------------------------------------------------------------------------------- 1 | // IIFE 2 | (function home(ax) { 3 | console.log(ax); 4 | })(12); 5 | (hend = (hendi) => { 6 | console.log("hend is :", hendi); 7 | })("indian"); 8 | (function (param) { 9 | console.log("name :", param); 10 | })("ali"); 11 | -------------------------------------------------------------------------------- /persian-articles-website.txt: -------------------------------------------------------------------------------- 1 | https://amirsalehi.ir/blog/ 2 | https://greenonsoftware.com/articles/integrations/how-to-integrate-state-management-in-zustand-with-nextjs/ 3 | https://greenonsoftware.com/articles/react/common-mistakes-in-using-react-context-api/ 4 | -------------------------------------------------------------------------------- /.templates/react-basic/index.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | function __templateNameToPascalCase__() { 4 | return ( 5 |
6 | __templateNameToPascalCase__ 7 |
8 | ) 9 | } 10 | 11 | export default __templateNameToPascalCase__; 12 | -------------------------------------------------------------------------------- /.templates/react-constant/index.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | function __templateNameToPascalCase__() { 4 | return ( 5 |
6 | __templateNameToPascalCase__ 7 |
8 | ) 9 | } 10 | 11 | export default __templateNameToPascalCase__; 12 | -------------------------------------------------------------------------------- /Javascript/first-class entity.js: -------------------------------------------------------------------------------- 1 | // first-class entity 2 | const hello = () => { 3 | console.log("hello f-c"); 4 | }; 5 | 6 | function say(handler) { 7 | handler(); 8 | 9 | return function () { 10 | console.log("goodbye f-c"); 11 | }; 12 | } 13 | 14 | console.log(say(hello)()); 15 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/App.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./App.css"; 3 | import FetchAPI from "./components/API/FetchApi"; 4 | 5 | function App() { 6 | return ( 7 |
8 | 9 |
10 | ); 11 | } 12 | 13 | export default App; 14 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/setupTests.js: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /Javascript/data-destructuring.js: -------------------------------------------------------------------------------- 1 | const num = [1, 2, 3, 4]; 2 | 3 | const [a, b, ...rest] = num; 4 | 5 | console.log(a, b, rest); 6 | 7 | // ============================ 8 | 9 | const user = { 10 | name: "eliot", 11 | age: 23, 12 | }; 13 | 14 | const { name } = user; 15 | 16 | console.log(name); 17 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/ErrorBoundaries/ErrorDemo.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | function ErrorDemo(props) { 4 | if (props.name != "codebucks") { 5 | throw new Error("There is an Error!"); 6 | } 7 | 8 | return
{props.name}
; 9 | } 10 | 11 | export default ErrorDemo; 12 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Ref/ChildRef.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const ChildRef = React.forwardRef((props, ref) => ( 4 |
5 |

Child Ref:

6 | 7 |
8 | )); 9 | 10 | export default ChildRef; 11 | -------------------------------------------------------------------------------- /Javascript/Currying_ChainClosure.js: -------------------------------------------------------------------------------- 1 | const sum = (a) => { 2 | return (sum1 = (b) => { 3 | return (sum2 = (c) => { 4 | return a + b + c; 5 | }); 6 | }); 7 | }; 8 | 9 | console.log(sum(2)(1)(3)); 10 | 11 | const sum1 = sum(1); 12 | const sum2 = sum1(6); 13 | const result = sum2(4); 14 | console.log(result); 15 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Fragments/Columns.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class Columns extends Component { 4 | render() { 5 | return ( 6 | 7 | Hello 8 | World 9 | 10 | ); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /reactQuery-keys.ts: -------------------------------------------------------------------------------- 1 | const userKeys = { 2 | all: ['users'] as const, 3 | lists: () => [...userKeys.all, 'list'] as const, 4 | list: (filters: string) => [...userKeys.lists(), { filters }] as const, 5 | details: () => [...userKeys.all, 'detail'] as const, 6 | detail: (id: number) => [...userKeys.details(), id] as const, 7 | }; 8 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from '@testing-library/react'; 3 | import App from './App'; 4 | 5 | test('renders learn react link', () => { 6 | const { getByText } = render(); 7 | const linkElement = getByText(/learn react/i); 8 | expect(linkElement).toBeInTheDocument(); 9 | }); 10 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Event Handling/ChildofClassComponent.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class ChildofClassComponent extends Component { 4 | render() { 5 | return ( 6 |
7 | 8 |
9 | ); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Fragments/TableDemo.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import Columns from "./Columns"; 3 | 4 | export default class TableDemo extends Component { 5 | render() { 6 | return ( 7 | 8 | 9 | 10 | 11 |
12 | ); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /React js/ForwardingRef.jsx: -------------------------------------------------------------------------------- 1 | // برای انتقال رف از یک کامپوننت به یک کامپوننت دیگر 2 | 3 | const FancyButton = React.forwardRef((props, ref) => ( 4 | 7 | )); 8 | 9 | // You can now get a ref directly to the DOM button: 10 | const ref = React.createRef(); 11 | Click me!; -------------------------------------------------------------------------------- /Javascript/null vs undefined.js: -------------------------------------------------------------------------------- 1 | const user = {}; 2 | console.log(user.name); // undefined 3 | 4 | let x; 5 | console.log(x); // undefined 6 | 7 | function person() { 8 | // no return 9 | } 10 | console.log(person()); // undefined 11 | 12 | nul == undefined; // true 13 | nul === undefined; // false 14 | 15 | console.log(typeof undefined); // undefined 16 | console.log(typeof null); // object 17 | -------------------------------------------------------------------------------- /React js/Ref.jsx: -------------------------------------------------------------------------------- 1 | // به مقادیر یک المنت دسترسی داشته باشیم 2 | 3 | import React, { useRef, useEffect } from "react"; 4 | 5 | function Ref() { 6 | const inputRef = useRef(); 7 | 8 | useEffect(() => { 9 | inputRef.current.focus(); 10 | }); 11 | 12 | return ( 13 |
14 | 15 |
16 | ); 17 | } 18 | 19 | export default Ref; 20 | -------------------------------------------------------------------------------- /Javascript/closure.js: -------------------------------------------------------------------------------- 1 | function init() { 2 | var count = 0; 3 | 4 | return function () { 5 | count++; 6 | return count; 7 | }; 8 | } 9 | 10 | const jump = init(); 11 | const fly = init(); 12 | 13 | console.log(jump()); 14 | console.log(jump()); 15 | console.log("=========="); 16 | console.log(fly()); 17 | console.log(fly()); 18 | console.log(!!init); // will be true --> !! Bolean mikone 19 | -------------------------------------------------------------------------------- /font-preload.js: -------------------------------------------------------------------------------- 1 | // in nextjs --> _app.js 2 | 9 | 10 | // in nextjs --> _document.js 11 | 18 | -------------------------------------------------------------------------------- /React-Tutorials-main/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Portals/ChildComponent.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import ReactDOM from "react-dom"; 3 | 4 | export default class ChildComponent extends Component { 5 | render() { 6 | return ReactDOM.createPortal( 7 |
8 | 9 |
, 10 | 11 | document.getElementById("portal") 12 | ); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Fragments/FragmentDemo.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import TableDemo from "./TableDemo"; 3 | import ListDemo from "./ListDemo"; 4 | 5 | export default class FragmentDemo extends Component { 6 | render() { 7 | return ( 8 | <> 9 |

This is Fragment Demo!


10 |
11 | 12 | 13 | ); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /Javascript/for.js: -------------------------------------------------------------------------------- 1 | // for in --> return index 2 | const number = [2, 6, 4, 8, 1]; 3 | for (const index in number) { 4 | console.log(number[index]); 5 | } 6 | 7 | const obj = { 8 | name: "abraham", 9 | age: 25, 10 | country: "england", 11 | }; 12 | for (const key in obj) { 13 | console.log(key); // key 14 | console.log(obj[key]); //value 15 | } 16 | 17 | 18 | // for of --> return item 19 | const num = [0, 7, 4, 9, 2]; 20 | for (const item of num) { 21 | console.log(item); 22 | } 23 | -------------------------------------------------------------------------------- /Javascript/prevState.js: -------------------------------------------------------------------------------- 1 | const [num, setNum] = useState(0); 2 | 3 | const handleClick = () => { 4 | setNum(num + 1); 5 | setNum(num + 1); // faghat 1 doone ezaf mishe 6 | setNum(num + 1); 7 | }; 8 | 9 | const handleClick2 = () => { 10 | setNum((prevState) => prevState + 1); 11 | setNum((prevState) => prevState + 1); // intori 3ta 3ta ezaf mishe 12 | setNum((prevState) => prevState + 1); 13 | }; 14 | 15 | // har mooghe be meghdar ghabli state niaz dashtim az prevState estefade mikonim 16 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/HOC/CommentsCount.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import HOC from "./HOC"; 3 | 4 | class CommentsCount extends Component { 5 | render() { 6 | return ( 7 |
8 | Total Comments : {this.props.CountNumber}
9 | 10 |
11 | ); 12 | } 13 | } 14 | 15 | const EnhancedComments = HOC(CommentsCount, 10); 16 | 17 | export default EnhancedComments; 18 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Event Handling/FunctionalComponent.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | export default function FunctionalComponent() { 4 | function clickHandler(event) { 5 | event.preventDefault(); 6 | console.log("Form is Submitted!"); 7 | } 8 | 9 | return ( 10 |
11 |
clickHandler(e)}> 12 | 13 | 14 |
15 |
16 | ); 17 | } 18 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/HOC/LikesCount.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import HOC from "./HOC"; 3 | 4 | class LikesCount extends Component { 5 | render() { 6 | return ( 7 |
8 | Hello {this.props.username}.
9 | {this.props.CountNumber}
10 | 11 |
12 | ); 13 | } 14 | } 15 | 16 | const EnhancedLikes = HOC(LikesCount, 5); 17 | 18 | export default EnhancedLikes; 19 | -------------------------------------------------------------------------------- /Javascript/HOF.js: -------------------------------------------------------------------------------- 1 | // HOF --> higher order function 2 | 3 | // const adder = (a) => { 4 | // return function (n) { 5 | // return a + n 6 | // } 7 | // } 8 | // const add5 = adder(5) 9 | // console.log('adder :', add5(5)) 10 | 11 | const newPush = (value) => { 12 | return (arr) => { 13 | const clone = [...arr, value]; 14 | return clone; 15 | }; 16 | }; 17 | 18 | const push1 = newPush(5); 19 | const arr = [1, 2, 3, 4]; 20 | 21 | console.log("arr :", arr); 22 | console.log("push1 :", push1(arr)); 23 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import "./index.css"; 4 | import App from "./App"; 5 | import * as serviceWorker from "./serviceWorker"; 6 | 7 | ReactDOM.render(, document.getElementById("root")); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /Javascript/msgChatScrollBottom.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useRef } from 'react' 2 | 3 | const Messages = ({ messages }) => { 4 | 5 | const messagesEndRef = useRef(null) 6 | 7 | const scrollToBottom = () => { 8 | messagesEndRef.current.scrollIntoView({ behavior: "smooth" }) 9 | } 10 | 11 | useEffect(scrollToBottom, [messages]); 12 | 13 | return ( 14 |
15 | {messages.map(message => )} 16 |
17 |
18 | ) 19 | } 20 | -------------------------------------------------------------------------------- /remove_duplicates.js: -------------------------------------------------------------------------------- 1 | const numbers = [3, 4, 2, 3, 7, 3]; 2 | 3 | const filterArr2 = numbers.filter((item, index, arr) => arr.indexOf(item) === index) // way 1 4 | 5 | const filterArr3 = [...new Set(numbers)] // way 2 6 | 7 | const filterArr4 = numbers.reduce((acc, val) => { 8 | acc.includes(val) ? acc : [...acc, val] 9 | },[]) // way 3 10 | 11 | // array of obj 12 | const removeDuplicatedArrObj = products?.filter( 13 | (firstValue, index, array) => 14 | index === array?.findIndex((secondValue) => secondValue?.productId === firstValue?.productId) 15 | ); 16 | -------------------------------------------------------------------------------- /Javascript/value_refrence_type.js: -------------------------------------------------------------------------------- 1 | // --------> primitive type (value type) = doesn't change 2 | // let x = 10; 3 | // let x = 'one'; 4 | // let x = null; 5 | // let x = false; 6 | 7 | // let y = x; 8 | 9 | // x = 20; 10 | // x = 'two'; 11 | // x = undefined; 12 | // x = true; 13 | 14 | // --------> refrence type = gonna change 15 | // let x = {val: 10}; 16 | // let x = [10] 17 | // function x() { 18 | // return 10; 19 | // } 20 | 21 | // let y = x; 22 | 23 | // x.val = 20; 24 | // x[0] = 20; 25 | // function x() { 26 | // return 20; 27 | // } 28 | 29 | // console.log(y()) 30 | // console.log(y) 31 | -------------------------------------------------------------------------------- /React js/LifeCycle.jsx: -------------------------------------------------------------------------------- 1 | // Mounting ---> component will ready to run in the DOM 2 | // Updating ---> update component with state - props 3 | // Unmounting ---> remove the component from DOM 4 | 5 | // ==================================== 6 | 7 | //Mount 8 | // 1- constructor() 9 | // 2- static getDerivedStateFormProps() 10 | // 3- render() 11 | // 4- componentDidMount() 12 | 13 | // Updating 14 | // 1- static getDerivedStateFromProps() 15 | // 2- shouldComponentUpdate() 16 | // 3- render() 17 | // 4- getSnapshotsBeforeUpdating() 18 | // 5- componentDidUpdate() 19 | 20 | // Unmount 21 | // 1- componentWillUnmount() 22 | -------------------------------------------------------------------------------- /Javascript/filter.js: -------------------------------------------------------------------------------- 1 | // filter 2 | const filter = (array, conditionFunc) => { 3 | if ( 4 | !Array.isArray(array) || 5 | array.length === 0 || 6 | typeof conditionFunc !== "function" 7 | ) { 8 | return []; 9 | } 10 | 11 | const result = []; 12 | // for (const item of array) { 13 | for (const index in array) { 14 | if (conditionFunc(array[index])) { 15 | result.push(array[index]); 16 | } 17 | } 18 | 19 | return result; 20 | }; 21 | 22 | const testFilter = filter([1, 2, 3, 4], function (item, index, array) { 23 | return item % 2 === 0; 24 | }); 25 | console.log("test filter :", testFilter); 26 | -------------------------------------------------------------------------------- /React-Tutorials-main/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Portals/ParentComponent.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import ChildComponent from "./ChildComponent"; 3 | 4 | export default class ParentComponent extends Component { 5 | constructor(props) { 6 | super(props); 7 | 8 | this.state = { 9 | count: 0, 10 | }; 11 | } 12 | 13 | onIncrement = () => { 14 | this.setState({ count: this.state.count + 1 }); 15 | }; 16 | 17 | render() { 18 | return ( 19 |
20 | Count Number: {this.state.count} 21 | 22 |
23 | ); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Props/Cars.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import CarDetails from "./CarDetails"; 3 | 4 | const carObj = { 5 | name: "Audi A5", 6 | color: "black", 7 | type: "sedan", 8 | }; 9 | 10 | export default function Cars() { 11 | return ( 12 |
13 | {/* //Child component to render Car Details */} 14 | 15 | 16 | {/* 17 | 18 | 19 | */} 20 |
21 | ); 22 | } 23 | -------------------------------------------------------------------------------- /React js/Responsive.css: -------------------------------------------------------------------------------- 1 | @media (max-width: 480px) { 2 | .bala { 3 | color: red; 4 | } 5 | 6 | .paiin { 7 | color: chartreuse; 8 | } 9 | } 10 | 11 | @media (min-width: 480px) { 12 | .bala { 13 | color: aqua; 14 | } 15 | 16 | .paiin { 17 | color: blue; 18 | } 19 | } 20 | 21 | /* 22 | 23 | 24 | 25 |

bala

26 | 27 |

Resize the browser window. When the width of this document is 600 pixels or less, the background-color is "lightblue", otherwise it is "lightgreen".

28 | 29 |

paiin

30 | 31 | 32 | 33 | */ 34 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Props/CarDetails.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class CarDetails extends Component { 4 | constructor(props) { 5 | super(props); 6 | } 7 | render() { 8 | return ( 9 |
17 |

Name:

{this.props.data.name}
18 |

Color:

{this.props.data.color}
19 |

Type:

{this.props.data.type}
20 |
21 | ); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/PureComponent/NormalComponent.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class NormalComponent extends Component { 4 | constructor(props) { 5 | super(props); 6 | 7 | this.state = { 8 | count: 0, 9 | }; 10 | } 11 | 12 | onIncrement = () => { 13 | this.setState({ count: 0 }); 14 | }; 15 | 16 | render() { 17 | console.log("Normal Component render method called!"); 18 | return ( 19 |
20 |

Normal Component


21 | {this.state.count} 22 | 23 |
24 | ); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /iphone zoom disable.css: -------------------------------------------------------------------------------- 1 | 2 | input[type="color"], 3 | input[type="date"], 4 | input[type="datetime"], 5 | input[type="datetime-local"], 6 | input[type="email"], 7 | input[type="month"], 8 | input[type="number"], 9 | input[type="password"], 10 | input[type="search"], 11 | input[type="tel"], 12 | input[type="text"], 13 | input[type="time"], 14 | input[type="url"], 15 | input[type="week"], 16 | select:focus, 17 | textarea { 18 | font-size: 16px !important; 19 | } 20 | 21 | input, select { 22 | font-size: 16px !important; 23 | } 24 | 25 | 26 | @media screen and (-webkit-min-device-pixel-ratio:0) { 27 | select, 28 | textarea, 29 | input { 30 | font-size: 16px !important; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Fragments/ListDemo.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class ListDemo extends Component { 4 | render() { 5 | const colors = [ 6 | { 7 | id: 1, 8 | color: "red", 9 | }, 10 | { 11 | id: 2, 12 | color: "blue", 13 | }, 14 | { 15 | id: 3, 16 | color: "green", 17 | }, 18 | { 19 | id: 4, 20 | color: "yellow", 21 | }, 22 | ]; 23 | return ( 24 | <> 25 | {colors.map((item) => ( 26 | {item.color} 27 | ))} 28 | 29 | ); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Lifecycle Methods/DisplayClock.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import Clock from "./Clock"; 3 | 4 | export default class DisplayClock extends Component { 5 | constructor(props) { 6 | super(props); 7 | 8 | this.state = { 9 | show: true, 10 | }; 11 | } 12 | 13 | deleteClock = () => { 14 | this.setState({ 15 | show: !this.state.show, 16 | }); 17 | }; 18 | 19 | render() { 20 | return ( 21 |
22 | {this.state.show ? :

Clock is removed

} 23 |
24 | 25 | 26 |
27 | ); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/PureComponent/PureComponents.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { PureComponent } from "react"; 3 | 4 | 5 | export default class PureComponents extends PureComponent { 6 | constructor(props) { 7 | super(props); 8 | 9 | this.state = { 10 | count: 0, 11 | }; 12 | } 13 | 14 | onIncrement = () => { 15 | this.setState({ count: 0 }); 16 | }; 17 | 18 | render() { 19 | console.log("Pure Component render method called!"); 20 | return ( 21 |
22 |

Pure Component


23 | {this.state.count} 24 | 25 |
26 | ); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Javascript/callback.js: -------------------------------------------------------------------------------- 1 | function download(url, callback) { 2 | setTimeout(() => { 3 | console.log(`downloading ${url}`); 4 | 5 | callback(url); 6 | }, 3000); 7 | } 8 | 9 | function process(pic) { 10 | console.log(`process ${pic}`); 11 | } 12 | 13 | let url = "https://javascripttutorial.net/pic.png"; 14 | 15 | download(url, process); 16 | 17 | // first download 18 | // after that process 19 | 20 | // callback hamoon async/await ast 21 | // vaghti az callback function estefade mikonim 22 | // yani inke be tartib saf anjam bede , yani oon time ezafi ro sabr kon 23 | 24 | // 1- callback function --> problem : callback hell 25 | // 2- promise function --> problem : nested then 26 | // 3- async/await function --> indeal 27 | -------------------------------------------------------------------------------- /Javascript/callStack.js: -------------------------------------------------------------------------------- 1 | // Call Stack = 'run codes here' 2 | 3 | // Browser API = 'all async function goes here such as setTimeOut, setInterval, Promis, asyncAwait' 4 | 5 | // MicroTask Queue = 'setTimeOut , setInterval' 6 | 7 | // MacroTask Queue = 'Promis, asyncAwait' 8 | 9 | // ========================== 10 | 11 | setTimeout(() => { 12 | console.log("time out 2000ms"); 13 | }, 2000); 14 | 15 | setTimeout(() => { 16 | console.log("time out 0ms"); 17 | }, 0); 18 | 19 | Promise.resolve("promis").then((res) => console.log(res)); 20 | 21 | let test = 1; 22 | let stop = 3; 23 | console.log("start busy-async"); 24 | while (test < stop) { 25 | console.log("in the while"); 26 | test++; 27 | } 28 | console.log("end busy-async"); 29 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/ErrorBoundaries/CounterDemo.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class CounterDemo extends Component { 4 | constructor(props) { 5 | super(props); 6 | 7 | this.state = { 8 | count: 0, 9 | }; 10 | } 11 | 12 | handleClick = () => { 13 | this.setState({ 14 | count: this.state.count + 1, 15 | }); 16 | }; 17 | 18 | render() { 19 | if (this.state.count === 5) { 20 | throw new Error("Error Occured!"); 21 | } else { 22 | return ( 23 |
24 | {this.state.count} 25 | 26 | 27 |
28 | ); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Ref/ParentRef.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import ChildRef from "./ChildRef"; 3 | 4 | export default class ParentRef extends Component { 5 | constructor(props) { 6 | super(props); 7 | 8 | this.myRef = React.createRef(); 9 | } 10 | onClick = () => { 11 | this.myRef.current.focus(); 12 | this.myRef.current.placeholder = "Button Clicked!"; 13 | console.log("Value ", this.myRef.current.value); 14 | }; 15 | 16 | render() { 17 | return ( 18 |
19 |

Parent Ref:

20 | 21 | 22 |
23 | ); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | pointer-events: none; 8 | } 9 | 10 | @media (prefers-reduced-motion: no-preference) { 11 | .App-logo { 12 | animation: App-logo-spin infinite 20s linear; 13 | } 14 | } 15 | 16 | .App-header { 17 | background-color: #282c34; 18 | min-height: 100vh; 19 | display: flex; 20 | flex-direction: column; 21 | align-items: center; 22 | justify-content: center; 23 | font-size: calc(10px + 2vmin); 24 | color: white; 25 | } 26 | 27 | .App-link { 28 | color: #61dafb; 29 | } 30 | 31 | @keyframes App-logo-spin { 32 | from { 33 | transform: rotate(0deg); 34 | } 35 | to { 36 | transform: rotate(360deg); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Javascript/object.keys.js: -------------------------------------------------------------------------------- 1 | const num = [1, 5, 2, 4, 8]; 2 | const obj = { a: 1, b: 2 }; 3 | 4 | const numKey = Object.keys(num); // ["0", "1", "2", "3", "4"] 5 | const numValue = Object.values(num); // [1, 5, 2, 4, 8] 6 | const objKey = Object.keys(obj); // ["a", "b"] 7 | const objValue = Object.values(obj); // [1, 2] 8 | 9 | console.log(numKey); 10 | console.log(numValue); 11 | console.log(objKey); 12 | console.log(objValue); 13 | 14 | const object1 = { 15 | a: "somestring", 16 | b: 42, 17 | }; 18 | 19 | for (const [key, value] of Object.entries(object1)) { 20 | console.log(`${key}: ${value}`); 21 | } 22 | 23 | function devide(weight) { 24 | let w1 = [...Array(weight).keys()]; 25 | // let w1 = Array.from(Array(weight).keys()); 26 | console.log(w1) 27 | } -------------------------------------------------------------------------------- /local-fonts.js: -------------------------------------------------------------------------------- 1 | // localFonts.js 2 | import localFont from '@next/font/local'; 3 | 4 | // local fonts 5 | export const dana = localFont({ 6 | src: [ 7 | { 8 | path: '../public/fonts/dana/Dana.ttf', 9 | weight: 'normal' 10 | } 11 | ], 12 | preload: true, 13 | variable: '--font-dana', 14 | }) 15 | 16 | export const danaBold = localFont({ 17 | src: [ 18 | { 19 | path: '../public/fonts/dana/Dana-Bold.ttf', 20 | weight: 'bold' 21 | } 22 | ], 23 | preload: true, 24 | variable: '--font-danaBold', 25 | }) 26 | 27 | // _app.js 28 | import { dana, danaBold } from './localFonts' 29 | 30 |
31 | {getLayout(, pageProps)} 32 |
33 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Ref/RefDemo.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class RefDemo extends Component { 4 | constructor(props) { 5 | super(props); 6 | 7 | this.inputRef = React.createRef(); 8 | } 9 | componentDidMount() { 10 | this.inputRef.current.focus(); 11 | this.inputRef.current.placeholder = "Placeholder Value"; 12 | console.log("ClassName is --> ", this.inputRef.current.className); 13 | } 14 | onSubmit = () => { 15 | console.log(this.inputRef.current.value); 16 | }; 17 | 18 | render() { 19 | return ( 20 |
21 | 22 | 23 |
24 | ); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Javascript/outside.js: -------------------------------------------------------------------------------- 1 | let li = Array.from(document.getElementsByClassName("li")); 2 | let span = document.getElementById("span"); 3 | 4 | li.map((item, index, arr) => { 5 | item.addEventListener("click", (e) => { 6 | // item.style.opacity = "1"; 7 | span.innerHTML = `your choice : ${e.target.textContent}`; 8 | 9 | li.map((item1, index1) => { 10 | index === index1 11 | ? (item1.style.opacity = "1") 12 | : (item1.style.opacity = ".5"); 13 | }); 14 | }); 15 | }); 16 | 17 | document.addEventListener("click", (e) => { 18 | if ( 19 | li.reduce((acc, val) => { 20 | return acc && !val.contains(e.target); 21 | }, true) 22 | ) { 23 | li.map((item) => { 24 | item.style.opacity = ".5"; 25 | span.innerHTML = ""; 26 | }); 27 | } 28 | }); 29 | -------------------------------------------------------------------------------- /Javascript/var const let.js: -------------------------------------------------------------------------------- 1 | Hoisting; 2 | // console.log(x) 3 | // var x = 2 4 | // =========================> undefined for var 5 | // var x = undefined 6 | // console.log(x) 7 | // x = 2 8 | 9 | // console.log(x) 10 | // let x = 2 11 | // =========================> err for let const 12 | // let x = err 13 | // console.log(x) 14 | // x = 2 15 | 16 | 1; 17 | // let, const = block scope 18 | // var = function scope 19 | 20 | 2; 21 | // var, let = assignable 22 | // const = can't assign 23 | 24 | 3; 25 | // var = Hoisting undefined 26 | // let, const = Hoisting Error 27 | 28 | // ====================================== 29 | scoping; 30 | 31 | { 32 | let x = 10; // error 33 | const y = 20; // error 34 | var z = 30; // 30 35 | } 36 | 37 | console.log(x); // error 38 | console.log(y); // error 39 | console.log(z); // 30 40 | -------------------------------------------------------------------------------- /React js/Portals.jsx: -------------------------------------------------------------------------------- 1 | 2 |
3 |
{/* create portal root */} 4 | 5 | 6 | 7 | // ============================ 8 | import React, { Component } from 'react'; 9 | import ReactDOM from 'react-dom'; 10 | 11 | // portal root 12 | const portalRoot = document.getElementById('portal-root'); 13 | 14 | export class Modal extends Component { 15 | render() { 16 | return ( 17 | ReactDOM.createPortal( 18 | <> 19 |

hello

20 |
{children}
21 | , 22 | portalRoot 23 | ) 24 | ) 25 | } 26 | } 27 | 28 | export class PortalComponent extends Component { 29 | render() { 30 | return ( 31 | 32 |

hello portal react

33 |
34 | ) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /React js/Error Boundary.jsx: -------------------------------------------------------------------------------- 1 | // error boundary like problem in internet 2 | 3 | class ErrorBoundary extends React.Component { 4 | constructor(props) { 5 | super(props); 6 | this.state = { hasError: false }; 7 | } 8 | 9 | componentDidCatch(error, info) { 10 | // You can also log the error to an error reporting service 11 | logErrorToMyService(error, info); 12 | } 13 | 14 | static getDerivedStateFromError(error) { 15 | // Update state so the next render will show the fallback UI. 16 | return this.setState({ hasError: true }); 17 | return { hasError: true }; 18 | } 19 | 20 | render() { 21 | if (this.state.hasError) { 22 | // You can render any custom fallback UI 23 | return

{"Something went wrong Erorr"}

; 24 | } 25 | return this.props.children; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/HOC/HOC.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | const HOC = (Component, data) => { 4 | //console.log("data", data); 5 | 6 | return class extends React.Component { 7 | constructor(props) { 8 | super(props); 9 | 10 | this.state = { 11 | count: data, 12 | name: JSON.stringify(localStorage.getItem("username")), 13 | }; 14 | } 15 | 16 | handleCLick = () => { 17 | this.setState({ 18 | count: this.state.count + 1, 19 | }); 20 | }; 21 | 22 | render() { 23 | return ( 24 | 29 | ); 30 | } 31 | }; 32 | }; 33 | 34 | export default HOC; 35 | -------------------------------------------------------------------------------- /React js/useMemo useCallback.js: -------------------------------------------------------------------------------- 1 | const memoizedValue = useMemo(() => func, [prop]); // khode function ro ejra mikone --> value memoize mishe 2 | const memoizedCallback = useCallback(func, [prop]); // yek callback function barmigardoone vs az ijad mojaddad an prevent mikone vaghti mikhahim be component child prop konim estefade mikonim --> function memoize mishe 3 | 4 | const App = () => { 5 | const fooFunction = () => { 6 | return "Foo is just Food without D"; 7 | }; 8 | const useMemoResult = React.useMemo(fooFunction, []); 9 | const useCallbackResult = React.useCallback(fooFunction, []); 10 | 11 | console.log("useMemoResult: ", useMemoResult); // useMemoResult: Foo is just Food without D 12 | console.log("useCallbackResult: ", useCallbackResult) // useCallbackResult: function fooFunction() {} 13 | 14 | return

Foo is just food without D

; 15 | }; 16 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Event Handling/ClassComponent.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import ChildofClassComponent from "./ChildofClassComponent"; 3 | 4 | export default class ClassComponent extends Component { 5 | constructor(props) { 6 | super(props); 7 | 8 | this.state = { 9 | name: "abc", 10 | }; 11 | 12 | // this.clickHandler = this.clickHandler.bind(this); 13 | } 14 | 15 | clickHandler = () => { 16 | console.log("Button is clicked in the class component"); 17 | console.log(this); 18 | 19 | this.setState({ 20 | name: "def", 21 | }); 22 | }; 23 | 24 | render() { 25 | return ( 26 |
27 |

{this.state.name}

28 | 29 |
30 | 31 |
32 | ); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /React js/Responsive.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | 3 | function Responsive() { 4 | const [windowWidth, setWindowWidth] = useState(); 5 | 6 | const handleResize = () => { 7 | setWindowWidth(window.innerWidth); 8 | }; 9 | 10 | useEffect(() => { 11 | window.addEventListener("resize", handleResize); 12 | 13 | return () => { 14 | window.removeEventListener("resize", handleResize); 15 | }; 16 | }, []); 17 | 18 | return ( 19 |
20 | 27 |

hello world

28 |
29 | ); 30 | } 31 | 32 | export default Responsive; 33 | 34 | // .mobile ---> setStyle for mobile breakPoint 35 | // .desktop ---> setStyle for desktop breakPoint 36 | -------------------------------------------------------------------------------- /React-Tutorials-main/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-advanced-practice", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^4.2.4", 7 | "@testing-library/react": "^9.5.0", 8 | "@testing-library/user-event": "^7.2.1", 9 | "react": "^16.13.1", 10 | "react-dom": "^16.13.1", 11 | "react-scripts": "3.4.3" 12 | }, 13 | "scripts": { 14 | "start": "react-scripts start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": { 23 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/ErrorBoundaries/ErrorBoundaries.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class ErrorBoundaries extends Component { 4 | constructor(props) { 5 | super(props); 6 | 7 | this.state = { 8 | hasError: false, 9 | error: "", 10 | errorInfo: "", 11 | }; 12 | } 13 | 14 | static getDerivedStateFromError(error) { 15 | return { hasError: true }; 16 | } 17 | 18 | componentDidCatch(error, errorInfo) { 19 | this.setState({ 20 | error: error, 21 | errorInfo: errorInfo, 22 | }); 23 | } 24 | 25 | render() { 26 | if (this.state.hasError) { 27 | return ( 28 |
29 |
Error:
{this.state.error.toString()}
30 |
Error Info:
{this.state.errorInfo.componentStack} 31 |
32 | ); 33 | } else { 34 | return this.props.children; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Conditional Rendering/ConditionalRendering.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class ConditionalRendering extends Component { 4 | constructor(props) { 5 | super(props); 6 | 7 | this.state = { 8 | name: "", 9 | }; 10 | } 11 | 12 | handleChange = (e) => { 13 | this.setState({ 14 | [e.target.name]: e.target.value, 15 | }); 16 | }; 17 | 18 | handleSubmit = (e) => { 19 | e.preventDefault(); 20 | 21 | console.log(this.state.name); 22 | }; 23 | 24 | render() { 25 | return ( 26 |
27 | {this.state.name &&

Hello {this.state.name}

}
28 |
29 | Name: {" "} 30 |
31 | 32 |
33 |
34 | ); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /nextjs-tips.txt: -------------------------------------------------------------------------------- 1 | attention web vitals 2 | use Next Image 3 | use zustand and implement "Hydration" 4 | for slider and carousel use "Keen Slider" 5 | multi zone for separate several apps 6 | next.config.js { 7 | config --> minimum CacheTTL on Images 8 | security headers 9 | } 10 | 11 | use sentry for monitoring and error tracking 12 | main page ---> ISR 13 | if you use SSR then use ssr-caching 14 | first image loaded ---> must be "priority" 15 | for Link default has prefetch=true ---> create custom linke component and make it prefetch=false 16 | use shallow routing for doesn't need make SSR or SSG 17 | for CSR use SWR 18 | use custom logger 19 | 20 | dynamic import SVG icons 21 | keep small return() method in pages and components 22 | if section of page doesn't need to be SSR--> make it dynamic import and { ssr: false } 23 | handleError in SSR, SSG, ... like try/catch 24 | use Headers vs Cookie in SSR 25 | use font loader in nextjs 26 | static pages like about-us policy and ... must be SSG 27 | -------------------------------------------------------------------------------- /Javascript/classes.js: -------------------------------------------------------------------------------- 1 | class person { 2 | constructor(name) { 3 | this.name = name; 4 | } 5 | 6 | sayPerson() { 7 | console.log(`person : hi my name is ${this.name}`); 8 | } 9 | } 10 | 11 | class student extends person { 12 | constructor(name, age, id) { 13 | super(name); 14 | this.age = age; 15 | this.id = id; 16 | } 17 | 18 | sayStudent() { 19 | console.log( 20 | `student : hi ${this.name} student ${this.age} age with id ${this.id}` 21 | ); 22 | } 23 | } 24 | 25 | class teacher extends person { 26 | constructor(name, lesson) { 27 | super(name); 28 | this.lesson = lesson; 29 | } 30 | 31 | sayTeacher() { 32 | console.log(`teacher : hi ${this.name} with lesson ${this.lesson} `); 33 | } 34 | } 35 | 36 | const john = new person("john"); 37 | john.sayPerson(); 38 | 39 | const student1 = new student("dele ali", 24, 10327); 40 | student1.sayStudent(); 41 | 42 | const teacher1 = new teacher("john abraham", "math"); 43 | teacher1.sayTeacher(); 44 | -------------------------------------------------------------------------------- /debounceFn.js: -------------------------------------------------------------------------------- 1 | export function debounce(func, timeout = 600) { 2 | let timer; 3 | const debounced = (...args) => { 4 | clearTimeout(timer); 5 | timer = setTimeout(() => { 6 | func.apply(this, args); 7 | }, timeout); 8 | }; 9 | debounced.cancel = () => { 10 | clearTimeout(timer); 11 | }; 12 | return debounced; 13 | } 14 | 15 | // usage 16 | 17 | const useSearchHook = (value) => { 18 | const [debouncedValue, setDebouncedValue] = useState(value); 19 | 20 | const debouncedSetValue = useMemo(() => debounce(setDebouncedValue, 500), []); 21 | 22 | useEffect(() => { 23 | debouncedSetValue(body); 24 | return () => { 25 | debouncedSetValue.cancel(); 26 | }; 27 | }, [value]); 28 | 29 | const { data, isLoading } = useQuery( 30 | [searchApiFunction, value], 31 | () => searchApiFunction(value), 32 | { retry: false } 33 | ); 34 | 35 | return { data, isLoading }; 36 | }; 37 | 38 | 39 | const { data, isLoading } = useSearchHook("text input value"); 40 | -------------------------------------------------------------------------------- /React js/React-Lazy.jsx: -------------------------------------------------------------------------------- 1 | // witout lazy 2 | import OtherComponent from './OtherComponent'; 3 | 4 | function MyComponent() { 5 | return ( 6 |
7 | 8 |
9 | ); 10 | } 11 | 12 | // with lazy 13 | import React, { lazy, Suspense } from 'react' 14 | const OtherComponent = lazy(() => import('./OtherComponent')); 15 | const AnotherComponent = lazy(() => import('./AnotherComponent')) 16 | 17 | function MyComponent() { 18 | return ( 19 |
20 | Loading...
}> 21 | 22 | 23 | 24 |
25 | ); 26 | } 27 | 28 | // وقتی که یک کاربر صحفه وبی را باز می کند، تمام محتوا به صورت یک جا بارگزاری می شود . بعضی از قسمت های محتوا اصلا کاربر به آن نیازی ندارد و به همین دلیل ، چرا چیز با ارزشی مثل وقت و یا پهنای باند و منابع را بیهوده هدر دهیم 29 | 30 | // استفاده می کنید کد های شما با استفاده از cra nextjs gatsby هنگامی که شما از 31 | // وب پک ترکیب میشه و هنگام بارگزاری همه فایل هارو یکجا بارگزاری میکنه 32 | 33 | -------------------------------------------------------------------------------- /testing.js: -------------------------------------------------------------------------------- 1 | Unit testing : Checks that individual units of code, mainly functions, work as expected ---> like a component 2 | tools: jest, @testing-library/react 3 | example: just test one thins, one section like fetch data but not real api, balke with mock fake data 4 | the unit test should not connect with external dependencies like db, api and ... 5 | 6 | Integration testing: Individual units or features of the app are combined and tested as a group ---> like some components works together 7 | tools: jest, @testing-library/react 8 | example: integration test is same with unit test but one different thing, the integration test is should connect with dependncies like api, db and ... not mock fake data 9 | 10 | End-to-end tests simulate actual user actions and are designed to test how a real user would likely use the application. 11 | In React, E2E testing helps to ensure that the code you wrote is functional and your app works as intended, allowing you 12 | to catch bugs in your code before your app is live. ---> an action like user's payment scenario 13 | tools: cypress 14 | -------------------------------------------------------------------------------- /Javascript/reduce.js: -------------------------------------------------------------------------------- 1 | // reduce 2 | const number = [2, 4, 7, 2, 5, 8, 5, 6, 4, 2, 4, 7, 2, 8, 4, 2, 5]; 3 | 4 | const repeat = (num) => { 5 | return number.reduce((acc, val) => (val === num ? ++acc : acc), 0); 6 | }; 7 | 8 | const max = (arr) => { 9 | return arr.reduce((acc, val) => (acc > val ? acc : val)); 10 | }; 11 | 12 | console.log("repeat :", repeat(4)); 13 | console.log("max :", max(number)); 14 | 15 | // =============================================== 16 | 17 | const fruits = ["apple", "orange", "apple", "banana"]; 18 | 19 | const tally = fruits.reduce((acc, val) => { 20 | if (acc[fruits]) { 21 | acc[fruits] = acc[fruits] + 1; 22 | } else { 23 | acc[fruits] = 1; 24 | } 25 | 26 | return acc; 27 | }, {}); 28 | 29 | console.log(tally); 30 | 31 | // =============================================== 32 | 33 | const arr = [ 34 | [1, 4, 2], 35 | [3, 7, 8], 36 | ]; 37 | 38 | const flattedArr = arr.reduce((acc, val) => { 39 | return [...acc, ...val]; 40 | }, []); 41 | 42 | console.log(flattedArr); 43 | 44 | // =============================================== 45 | -------------------------------------------------------------------------------- /React js/useDebounce.jsx: -------------------------------------------------------------------------------- 1 | import React, { useRef, useMemo, useLayoutEffect, useEffect } from 'react' 2 | 3 | 4 | function debounce(fn, delay) { 5 | let timer; 6 | 7 | return (...args) => { 8 | clearTimeout(timer) 9 | timer = setTimeout(() => { 10 | fn(...args) 11 | }, delay) 12 | } 13 | } 14 | 15 | 16 | const useDebounce = (callback, delay) => { 17 | 18 | const callbackRef = useRef(callback) 19 | 20 | useLayoutEffect(() => { 21 | callbackRef.current = callback 22 | }, [callback]) 23 | 24 | return useMemo(() => debounce(((...args) => callbackRef.current(...args)), delay), [delay]) 25 | 26 | } 27 | 28 | export default useDebounce 29 | 30 | // const cachedGetDataFunction = useCallback(async () => { 31 | // try { 32 | // await dispatch(loadItems({id: "esrafil"})).unwrap(); 33 | // } 34 | // } catch (error) { 35 | // console.log(error); 36 | // console.log("err in fetch data"); 37 | // } 38 | // }, [dependencies_needed]) 39 | 40 | // const getDouncedFunction = useDebounce(cachedGetDataFunction, 600); 41 | 42 | 43 | -------------------------------------------------------------------------------- /useDebounce.jsx: -------------------------------------------------------------------------------- 1 | import React, { useRef, useMemo, useLayoutEffect, useEffect } from 'react' 2 | 3 | 4 | function debounce(fn, delay) { 5 | let timer; 6 | 7 | return (...args) => { 8 | clearTimeout(timer) 9 | timer = setTimeout(() => { 10 | fn(...args) 11 | }, delay) 12 | } 13 | } 14 | 15 | 16 | const useDebounce = (callback, delay) => { 17 | 18 | const callbackRef = useRef(callback) 19 | 20 | useLayoutEffect(() => { 21 | callbackRef.current = callback 22 | }, [callback]) 23 | 24 | return useMemo(() => debounce(((...args) => callbackRef.current(...args)), delay), [delay]) 25 | 26 | } 27 | 28 | export default useDebounce 29 | 30 | // const cachedGetDataFunction = useCallback(async () => { 31 | // try { 32 | // await dispatch(loadItems({id: "esrafil"})).unwrap(); 33 | // } 34 | // } catch (error) { 35 | // console.log(error); 36 | // console.log("err in fetch data"); 37 | // } 38 | // }, [dependencies_needed]) 39 | 40 | // const getDouncedFunction = useDebounce(cachedGetDataFunction, 600); 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /useGeoLocation.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState, useMemo, useCallback } from 'react'; 2 | 3 | 4 | interface GeoPosition { 5 | latitude: number; 6 | longitude: number; 7 | } 8 | 9 | function useGeolocation() { 10 | const [geoPosition, setGeoPosition] = useState(null); 11 | const [geoError, setGeoError] = useState(null); 12 | 13 | const getCurrentPosition = useCallback(() => { 14 | if ("geolocation" in navigator) { 15 | navigator.geolocation.getCurrentPosition( 16 | (position) => { 17 | const { latitude, longitude } = position.coords 18 | setGeoPosition({ latitude, longitude }); 19 | }, 20 | (err) => { 21 | setGeoError(err.message); 22 | } 23 | ); 24 | } else { 25 | setGeoError("Geolocation is not available in this browser."); 26 | } 27 | }, []); 28 | 29 | useEffect(() => { 30 | getCurrentPosition(); 31 | }, [getCurrentPosition]); 32 | 33 | return useMemo(() => ({ geoPosition, geoError }), [geoPosition, geoError]); 34 | } 35 | 36 | export default useGeolocation; 37 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Lifecycle Methods/Clock.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class Clock extends Component { 4 | constructor(props) { 5 | super(props); 6 | 7 | this.state = { 8 | date: new Date(), 9 | count: 0, 10 | }; 11 | } 12 | 13 | componentDidMount() { 14 | setInterval(() => { 15 | this.tick(); 16 | }, 5000); 17 | } 18 | 19 | componentDidUpdate(prevProps, prevState, snapshot) { 20 | //we must put a condition before using setstate 21 | if (this.state.date !== prevState.date) { 22 | this.setState({ 23 | count: this.state.count + 1, 24 | }); 25 | } 26 | } 27 | 28 | componentWillUnmount() { 29 | alert("Clock Component Will Unmount!"); 30 | } 31 | 32 | tick = () => { 33 | this.setState({ 34 | date: new Date(), 35 | }); 36 | }; 37 | 38 | render() { 39 | return ( 40 |
41 |

Hello World!

42 | 43 |

It is {this.state.date.toLocaleTimeString()}.

44 | 45 |

This component is Updated {this.state.count} times.

46 |
47 | ); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /re-render.isx: -------------------------------------------------------------------------------- 1 | avoid re-render child component : 2 | 3 | // App.jsx 4 | import React, { useMemo, useState } from "react"; 5 | import Test from "./Test"; 6 | 7 | function App() { 8 | const [obj, setObj] = useState({ name: "esrafil" }); 9 | 10 | console.log("App re-render"); 11 | 12 | // the first way to avoid re-render ==> React.memo 13 | const memoizeObj = useMemo(() => { 14 | return obj; 15 | }, [obj.name]); 16 | // [obj] ===> not work 17 | 18 | return ( 19 |
20 | 21 | {obj.name} 22 | 23 |
24 | ); 25 | } 26 | 27 | export default App; 28 | 29 | 30 | 31 | // Test.jsx (Child component) 32 | import React from "react"; 33 | 34 | // the second way to avoid re-render ==> with React.memo 35 | const checkMemo = (prev, next) => { 36 | console.log({ prev: prev?.data?.name, next: next?.data?.name }); 37 | 38 | return prev?.data?.name !== next.data?.name; 39 | }; 40 | 41 | const Test = ({ data }) => { 42 | console.log("Test Component re-render"); 43 | 44 | return
{data.name}
; 45 | }; 46 | 47 | export default React.memo(Test, checkMemo); 48 | -------------------------------------------------------------------------------- /useDebounce-typescript.tsx: -------------------------------------------------------------------------------- 1 | import React, { useRef, useMemo, useLayoutEffect, useEffect } from "react"; 2 | 3 | // T === fn 4 | type AnyCallbackFunc = (...args: any[]) => any; 5 | type DebounceFunction = (fn: F, delay: number) => (...args: Parameters) => void; 6 | 7 | const debounce: DebounceFunction = (fn, delay) => { 8 | let timer: ReturnType; 9 | 10 | return (...args) => { 11 | clearTimeout(timer); 12 | timer = setTimeout(() => { 13 | fn(...args); 14 | }, delay); 15 | }; 16 | }; 17 | 18 | const useDebounce = (callback: AnyCallbackFunc, delay: number): AnyCallbackFunc => { 19 | const callbackRef = useRef(callback); 20 | 21 | useLayoutEffect(() => { 22 | callbackRef.current = callback; 23 | }, [callback]); 24 | 25 | return useMemo(() => debounce((...args) => callbackRef.current(...args), delay), [delay]); 26 | }; 27 | 28 | export default useDebounce; 29 | 30 | // const cachedGetDataFunction = useCallback(async () => { 31 | // try { 32 | // await dispatch(loadItems({id: "esrafil"})).unwrap(); 33 | // } 34 | // } catch (error) { 35 | // console.log(error); 36 | // console.log("err in fetch data"); 37 | // } 38 | // }, [dependencies_needed]) 39 | 40 | // const getDouncedFunction = useDebounce(cachedGetDataFunction, 600); 41 | -------------------------------------------------------------------------------- /template.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This file is a configuration file generated by the `Template` extension on `vscode` 3 | * @see https://marketplace.visualstudio.com/items?itemName=yongwoo.template 4 | */ 5 | module.exports = { 6 | // You can change the template path to another path 7 | templateRootPath: "./.templates", 8 | // After copying the template file the `replaceFileTextFn` function is executed 9 | replaceFileTextFn: (fileText, templateName, utils) => { 10 | // @see https://www.npmjs.com/package/change-case 11 | const { changeCase } = utils; 12 | // You can change the text in the file 13 | return fileText 14 | .replace(/__templateName__/g, templateName) 15 | .replace(/__templateNameToPascalCase__/g, changeCase.pascalCase(templateName)) 16 | .replace(/__templateNameToParamCase__/g, changeCase.paramCase(templateName)); 17 | }, 18 | renameFileFn: (fileName, templateName, utils) => { 19 | const { path } = utils; 20 | const { base } = path.parse(fileName); 21 | return base.replace(/__templateName__/gm, templateName); 22 | }, 23 | renameSubDirectoriesFn: (directoryName, templateName, _utils) => { 24 | const { changeCase } = _utils; 25 | const newDirectoryName = changeCase.paramCase(templateName); 26 | return directoryName.replace(/__templateName__/g, newDirectoryName); 27 | }, 28 | }; 29 | -------------------------------------------------------------------------------- /Javascript/promis.js: -------------------------------------------------------------------------------- 1 | // promise 2 | 3 | const handlePromis = new Promise((resolve, reject) => { 4 | setTimeout(() => { 5 | resolve("hello"); 6 | reject("error"); 7 | }, [1000]); 8 | }); 9 | 10 | handlePromis 11 | .then((res) => { 12 | console.log("res resolve :", res); 13 | }) 14 | .then(() => { 15 | console.log("res badesh : goodbye"); 16 | }) 17 | .catch(() => { 18 | console.log("err"); 19 | }); 20 | 21 | // another promise example 22 | 23 | const res = Promise.resolve("hello"); 24 | 25 | res 26 | .then((val) => { 27 | console.log(val); 28 | return `${val} world`; 29 | }) 30 | .then((newVal) => { 31 | console.log(newVal); 32 | }); 33 | 34 | const rej = Promise.reject("hello"); 35 | 36 | rej 37 | .catch((val) => { 38 | console.log(val); 39 | return Promise.reject(`${val} world`); 40 | }) 41 | .catch((newVal) => { 42 | console.log(newVal); 43 | }); 44 | 45 | // another promise example 46 | 47 | const prom = new Promise((resolve, reject) => { 48 | if (true) { 49 | reject(new Error("rejected!")); 50 | } else { 51 | resolve("resolved!"); 52 | } 53 | }); 54 | 55 | prom 56 | .then((val) => { 57 | return Promise.resolve(`${val} we did it!`); 58 | }) 59 | .then((val) => { 60 | console.log(`got ${val}`); 61 | }) 62 | .catch((err) => { 63 | console.log(`err msg : ${err.message}`); 64 | }); 65 | -------------------------------------------------------------------------------- /Javascript/this.js: -------------------------------------------------------------------------------- 1 | // ===================================== 2 | function foo() { 3 | console.log(this); 4 | } 5 | foo(); // window 6 | 7 | // ===================================== 8 | var name = "David"; 9 | function getName() { 10 | console.log(this.name); 11 | } 12 | getName(); 13 | 14 | // ===================================== 15 | const name = "David"; 16 | function getName() { 17 | console.log(this.name); 18 | } 19 | var obj = { 20 | name: "John", 21 | print: getName, 22 | }; 23 | obj.print(); 24 | 25 | // ===================================== 26 | var name = "David"; 27 | var person = { 28 | name: "John", 29 | getName: function () { 30 | console.log(this.name); 31 | }, 32 | }; 33 | var getName = person.getName; 34 | getName(); 35 | person.getName(); 36 | 37 | // ===================================== 38 | const person = { 39 | getName() { 40 | return this.name; 41 | }, 42 | }; 43 | const personA = { 44 | name: "John Doe", 45 | }; 46 | console.log(person.getName.apply(personA)); 47 | 48 | // ===================================== 49 | ("use strict"); 50 | function edge() { 51 | return this; 52 | } 53 | console.log(edge()); // undefined 54 | 55 | // ===================================== 56 | var name = "John"; 57 | const person = { 58 | name: "David", // in var const let nadare pas globale 59 | 60 | printName: () => { 61 | alert(this.name); 62 | }, 63 | }; 64 | 65 | person.printName(); 66 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/Forms/DemoForm.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | 3 | export default class DemoForm extends Component { 4 | constructor(props) { 5 | super(props); 6 | 7 | this.state = { 8 | form: { 9 | name: "", 10 | email: "", 11 | gender: "", 12 | }, 13 | }; 14 | } 15 | 16 | handleChange = (e) => { 17 | let name = e.target.name; 18 | let value = e.target.value; 19 | 20 | this.setState({ 21 | ...this.state.form, 22 | 23 | form: { 24 | ...this.state.form, 25 | [name]: value, 26 | }, 27 | }); 28 | }; 29 | 30 | handleSubmit = (e) => { 31 | e.preventDefault(); 32 | console.log(this.state.form); 33 | }; 34 | 35 | render() { 36 | return ( 37 |
38 |

Signup Form


39 |
40 | 41 | 42 |
43 | 44 | 45 | 46 |
47 | 48 | 49 | 54 |
55 | 56 | 57 |
58 |
59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /bind_call_apply.js: -------------------------------------------------------------------------------- 1 | // bind : The bind() method creates a new function and when that new function is called it set this keyword to the first argument which is passed to the bind method, and if any other sequences of arguments preceding the first argument are passed to the bind method then they are passed as an argument to the new function when the new function is called. 2 | 3 | let nameObj = { 4 | name: "Tony" 5 | } 6 | 7 | let PrintName = { 8 | name: "steve", 9 | sayHi: function () { 10 | 11 | // Here "this" points to nameObj 12 | console.log(this.name); 13 | } 14 | } 15 | 16 | let HiFun = PrintName.sayHi.bind(nameObj); 17 | HiFun(); 18 | 19 | 20 | 21 | // call : The call() method calls the function directly and sets this to the first argument passed to the call method and if any other sequences of arguments preceding the first argument are passed to the call method then they are passed as an argument to the function. 22 | 23 | let nameObj = { 24 | name: "Tony" 25 | } 26 | 27 | let PrintName = { 28 | name: "steve", 29 | sayHi: function (age) { 30 | console.log(this.name + " age is " + age); 31 | } 32 | } 33 | 34 | PrintName.sayHi.call(nameObj, 42); 35 | 36 | 37 | 38 | // apply : The apply() method calls the function directly and sets this to the first argument passed to the apply method and if any other arguments provided as an array are passed to the call method then they are passed as an argument to the function. 39 | 40 | let nameObj = { 41 | name: "Tony" 42 | } 43 | 44 | let PrintName = { 45 | name: "steve", 46 | sayHi: function (...age) { 47 | console.log(this.name + " age is " + age); 48 | } 49 | } 50 | PrintName.sayHi.apply(nameObj, [42]); 51 | -------------------------------------------------------------------------------- /React js/Controlled Uncontrolled Components.jsx: -------------------------------------------------------------------------------- 1 | //Controlled 2 | class NameForm extends React.Component { 3 | constructor(props) { 4 | super(props); 5 | this.state = { value: "" }; 6 | } 7 | 8 | handleChange(event) { 9 | this.setState({ value: event.target.value }); 10 | } 11 | 12 | handleSubmit(event) { 13 | alert("A name was submitted: " + this.state.value); 14 | event.preventDefault(); 15 | } 16 | 17 | render() { 18 | return ( 19 |
20 | 28 | 29 |
30 | ); 31 | } 32 | } 33 | 34 | // uncontrolled 35 | class NameForm extends React.Component { 36 | constructor(props) { 37 | super(props); 38 | this.input = React.createRef(); // create ref = value managed with DOM 39 | } 40 | 41 | handleSubmit(event) { 42 | const name = this._name; // intori ham mishe without create ref 43 | alert("A name was submitted: " + this.input.current.value); 44 | event.preventDefault(); 45 | } 46 | 47 | render() { 48 | return ( 49 |
50 | 56 | 57 |
58 | ); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /React-Tutorials-main/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 |
33 | 34 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Javascript/callBackOther.js: -------------------------------------------------------------------------------- 1 | // with callback function 2 | 3 | // console.log("start"); 4 | 5 | // function loginUser(email, callback) { 6 | // setTimeout(() => { 7 | // console.log("timeOut in loginUser"); 8 | // callback({ userEmail: email }); 9 | // }, 2000); 10 | // } 11 | 12 | // function userVideos(email, callback) { 13 | // setTimeout(() => { 14 | // console.log(`timeOut in userVideos : ${email}`); 15 | // callback(["v1", "v2", "v3"]); 16 | // }, 2000); 17 | // } 18 | 19 | // function videoDetails(callback) { 20 | // setTimeout(() => { 21 | // console.log(`video details`); 22 | // callback("video title"); 23 | // }, 2000); 24 | // } 25 | 26 | // const user = loginUser("essinho1121@gmail.com", (info) => { 27 | // console.log(info); 28 | // userVideos(info.userEmail, (videos) => { 29 | // console.log(videos); 30 | // videoDetails((title) => { 31 | // console.log(title); 32 | // }); 33 | // }); 34 | // }); 35 | 36 | // console.log("end"); 37 | 38 | // with promise 39 | 40 | console.log("start"); 41 | 42 | function loginUser(email) { 43 | return new Promise((resolve, reject) => { 44 | console.log("timeOut in loginUser"); 45 | setTimeout(() => { 46 | resolve({ userEmail: email }); 47 | }, 2000); 48 | }); 49 | } 50 | 51 | function userVideos(email) { 52 | return new Promise((resolve, reject) => { 53 | setTimeout(() => { 54 | console.log(`timeOut in userVideos : ${email}`); 55 | resolve(["v1", "v2", "v3"]); 56 | }, 2000); 57 | }); 58 | } 59 | 60 | function videoDetails() { 61 | return new Promise((resolve, reject) => { 62 | setTimeout(() => { 63 | console.log(`video details`); 64 | resolve("video title"); 65 | }, 2000); 66 | }); 67 | } 68 | 69 | console.log("end"); 70 | 71 | // loginUser("esrafil.elahi@gmail.com") 72 | // .then((user) => userVideos(user.userEmail)) 73 | // .then(() => videoDetails()); 74 | 75 | // with async await 76 | 77 | async function displayUser() { 78 | const logged = await loginUser("await@email.com"); 79 | const videos = await userVideos(logged.userEmail); 80 | const details = await videoDetails(); 81 | console.log(details); 82 | } 83 | 84 | displayUser(); 85 | -------------------------------------------------------------------------------- /testing-persian.js: -------------------------------------------------------------------------------- 1 | تست جعبه سفید (White-box Testing) 2 | 3 | در این نوع تست با مکانیسم داخلی و متدهای یک سیستم سرو کار داریم. به این نوع تست structural تست نیز گفته می‌شود. 4 | 5 | تست جعبه سیاه (Black-box Testing) 6 | 7 | در این رویکرد‌، تست تمامی مکانیسم‌های داخلی یک سیستم نادیده گرفته می‌شود و روی خروجی تولید شده تمرکز می‌شود.به این رویکرد تست functional نیز می‌گویند 8 | 9 | ====== 10 | 11 | یونیت تستینگ (Unit Testing) 12 | 13 | در این نوع تست ما یک واحد و یا یک گروه از واحد‌های مرتبط با هم را تست می‌کنیم. این نوع تست زیر مجموعه White-box Testing است. 14 | 15 | اینتگریشن تستینگ (Integration Testing) 16 | 17 | این نوع تست به ما این امکان را می‌دهد که چند نوع کامپننت مختلف را کنار یکدیگر تست کنیم. در این صورت حتی ما می‌توانیم وابستگی‌های میان سخت افزار و نرم افزار را نیز تست کنیم. این دسته از تست‌ها زیر مجموعه black box هستند. 18 | 19 | فانکشنال تستینگ (Functional Testing) 20 | 21 | در این تست اطمینان حاصل می‌شود که عملکرد برنامه به درستی است.توجه شود که در این نوع تست برخلاف آزمون واحد ما می‌توانیم عملکرد یک سیستم را تست کنیم و نه فقط یک واحد را.این تست زیر مجموعه black box هستند. 22 | 23 | سیستم تستینگ (System Testing) 24 | 25 | این نوع تست به ما اجازه می‌دهد که از عملکرد برنامه در محیطهای مختلف اطمینان حاصل کنیم(مثل سیستم عامل های مختلف). این تست زیر مجموعه black box تست‌ها است. 26 | 27 | استرس تستینگ (Stress Testing) 28 | 29 | این نوع تست عملکرد برنامه را در شرایط نا مطلوب مورد بررسی قرار می‌دهد. این تست زیر مجموعه black box تست‌ها است. 30 | 31 | پرفورمنس تستینگ (Performance Testing) 32 | 33 | تست عملکرد و کارایی که در مجموعه black box تست‌ها جای میگیرد به ما این اطمینان را می‌دهد که برنامه مان عملکرد و کارایی لازم را در یک مدت زمان مشخص داراست. 34 | 35 | یوزیبیلیتی تستینگ (Usability Testing) 36 | 37 | این تست از دیدگاه مشتری انجام می‌شود و در واقع مشخص کننده فاکتورهای زیر است: 38 | 39 | آیا برنامه کاربر پسند است؟ 40 | 41 | آیا برنامه ساده و قابل یادگیری است؟ 42 | 43 | آیا برنامه جذاب طراحی شده است؟ 44 | 45 | و … 46 | 47 | این نوع تست زیر مجموعه black box تست‌ها است. 48 | 49 | اکسپتنس تستینگ (Acceptance Testing) 50 | 51 | این نوع تست معمولا از طرف مشتری انجام می‌شود.هدف آن، مشخص کردن این است که آیا برنامه نیازهای مشتری را پاسخ می‌دهد و آیا برنامه همان چیزی که مشتری می‌خواهد هست یا خیر. 52 | 53 | رگرشن تستینگ (Regression Testing) 54 | 55 | این نوع تست به منظور صحت عملکرد سیستم بعد از تغییرات استفاده می‌شود و زیر مجموعه black box تست‌ها است. 56 | 57 | بتا تستینگ (Beta Testing) 58 | 59 | تستی است که توسط کاربر نهایی یا یک تیم خارج از تیم توسعه انجام می‌شود.هدف تست بتا پوشش دادن خطاهای غیر منتظره است.این تست زیر مجموعه black box تست‌ها است. 60 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /utils.ts: -------------------------------------------------------------------------------- 1 | // import axios from "./axios"; 2 | // import Cookies from 'js-cookie'; 3 | 4 | // work with numbers 5 | export const persianToEnglishDigits = (digit: number | string): string => 6 | String(digit) 7 | .replace(/[٠-٩]/g, (d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d).toString()) // Convert to string 8 | .replace(/[۰-۹]/g, (d) => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d).toString()); // Convert to string 9 | 10 | export const preventNumbersTyping = (str: string): string => str.replace(/[0-9]/g, ''); 11 | export const preventLettersTyping = (str: string): string => str.replace(/\D/g, ''); 12 | 13 | export const setNumberDigitAndPreventLettersTypes = (value: string | number): string => { 14 | return preventLettersTyping(persianToEnglishDigits(value)); 15 | }; 16 | 17 | // validation 18 | export const validateEmail = (email: string): RegExpMatchArray | null => { 19 | return String(email) 20 | .toLowerCase() 21 | .match(/^[A-Za-z0-9._%+-]{2,}@[A-Za-z0-9.-_]{2,}\.[A-Za-z]{2,}$/); 22 | }; 23 | export const phoneValidation = (value: string): boolean => { 24 | if (value.length !== 11) return false; 25 | if (!value.startsWith('09')) return false; 26 | return true; 27 | }; 28 | 29 | // for handling persian or english text direction 30 | export const isPersian = (str: string): boolean => { 31 | const PersianASCII: RegExp = /[آ-ی]|([a-zA-Z])/; 32 | 33 | if (str.match(PersianASCII) !== null) { 34 | if (str.match(PersianASCII)![1]) { 35 | return false; 36 | } 37 | return true; 38 | } 39 | return true; 40 | }; 41 | 42 | // detect device mode 43 | export const Android = () => { 44 | const ua = window.navigator.userAgent.toLowerCase(); 45 | return ua.indexOf('android') > -1; 46 | }; 47 | export const IOS = () => 48 | ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'].includes(window.navigator.platform) || 49 | // iPad on iOS 13 detection 50 | (window.navigator.userAgent.includes('Mac') && 'ontouchend' in document); 51 | 52 | // other helper functions 53 | export const timeConverter = (value: string) => { 54 | const sec: number | string = parseInt(value, 10); 55 | let hours: number | string = Math.floor(sec / 3600); 56 | let minutes: number | string = Math.floor((sec - hours * 3600) / 60); 57 | let seconds: number | string = sec - hours * 3600 - minutes * 60; 58 | if (hours < 10) { 59 | hours = `0${hours}`; 60 | } 61 | if (minutes < 10) { 62 | minutes = `0${minutes}`; 63 | } 64 | if (seconds < 10) { 65 | seconds = `0${seconds}`; 66 | } 67 | const time = `${minutes}:${seconds}`; 68 | return time; 69 | }; 70 | 71 | export const priceStringify = (num: string | number) => { 72 | let ans = String(num); 73 | for (let i = ans.length - 3; i > 0; i -= 3) { 74 | ans = `${ans.substring(0, i)},${ans.substring(i)}`; 75 | } 76 | return ans; 77 | }; 78 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/components/API/FetchApi.js: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | 3 | function FetchAPI() { 4 | 5 | const [data, setData] = useState([]); 6 | const [inputs, setInputs] = useState({}); 7 | 8 | //Get Method 9 | const apiGet = () => { 10 | fetch("https://jsonplaceholder.typicode.com/posts") 11 | .then((response) => response.json()) 12 | .then((json) => { 13 | console.log(json); 14 | setData(json); 15 | }); 16 | }; 17 | 18 | //Post Method 19 | const apiPost = async () => { 20 | await fetch("https://jsonplaceholder.typicode.com/posts", { 21 | method: "POST", 22 | body: JSON.stringify({ 23 | title: inputs.title, 24 | body: inputs.body, 25 | userId: parseInt(inputs.userId), 26 | }), 27 | headers: { 28 | "Content-type": "application/json; charset=UTF-8", 29 | }, 30 | }) 31 | .then((response) => response.json()) 32 | .then((json) => console.log(json)); 33 | }; 34 | 35 | const handleChange = (event) => { 36 | event.persist(); 37 | setInputs((inputs) => ({ 38 | ...inputs, 39 | 40 | [event.target.name]: event.target.value, 41 | })); 42 | }; 43 | 44 | const handleSubmit = (event) => { 45 | event.preventDefault(); 46 | apiPost(); 47 | console.log(inputs); 48 | }; 49 | 50 | // useEffect(() => { 51 | // apiGet(); 52 | // }, []); 53 | 54 | return ( 55 |
56 | My API
57 | 58 |
59 | {/*
{JSON.stringify(data, null, 2)}
*/} 60 |
61 |
    62 | {data.map((item) => ( 63 |
  • 64 | {item.userId},{item.title} 65 |
  • 66 | ))} 67 |
68 |
69 |
70 |
71 | {" "} 77 |
78 | 84 |
85 | 91 |
92 | 93 |
94 |
95 |
96 | ); 97 | } 98 | 99 | export default FetchAPI; 100 | -------------------------------------------------------------------------------- /Javascript/jsMethods.js: -------------------------------------------------------------------------------- 1 | const num = [1, 4, 0, 2, 7, 0, 3, 1, 4, 1, 4, 3, 1, 0]; 2 | const names = [ 3 | "esrafil", 4 | "parsa", 5 | "atrin", 6 | "zahra", 7 | "nasim", 8 | "nazanin", 9 | "shaghayegh", 10 | ]; 11 | const arrObj = [ 12 | { name: "tom", age: 25 }, 13 | { name: "larson", age: 23 }, 14 | { name: "tom", age: 25 }, 15 | { name: "edin", age: 20 }, 16 | { name: "tom", age: 23 }, 17 | { name: "larson", age: 19 }, 18 | ]; 19 | 20 | // random rendering 21 | let random = num.sort(() => { 22 | return Math.random() - 0.5; 23 | }); 24 | 25 | // repeat number 26 | let repeat = (repeatNum) => { 27 | return num.reduce((acc, value) => (value === repeatNum ? ++acc : acc), 0); 28 | }; 29 | 30 | // min, max number 31 | let max = num.reduce((acc, val) => (acc > val ? acc : val)); 32 | let min = num.reduce((acc, val) => (acc < val ? acc : val)); 33 | 34 | // filter name for --> na 35 | let nameFilter = []; 36 | 37 | for (let i = 0; i < names.length; i++) { 38 | let value = names[i]; 39 | if (value.startsWith("na") || value.substring(0, 2) === "na") { 40 | nameFilter.push(value); 41 | } 42 | } 43 | 44 | // filter name filter --> na 45 | let filterName = names.filter((name) => name.startsWith("na")); 46 | 47 | // unique item --> set 48 | let uniqueSet = [...new Set(num)]; 49 | let newSet1 = new Set(num); 50 | let newSet2 = [...newSet1]; 51 | let newSet3 = Array.from(newSet1); 52 | 53 | // unique item --> filter 54 | let uniqueFilter = num.filter( 55 | (value, index, array) => array.indexOf(value) === index 56 | ); 57 | let notUniqueFilter = num.filter( 58 | (value, index, array) => array.indexOf(value) !== index 59 | ); 60 | 61 | // unique item --> reduce 62 | let uniqueReduce = num.reduce( 63 | (acc, val) => (acc.includes(val) ? acc : [...acc, val]), 64 | [] 65 | ); 66 | 67 | // unique array of obj --> set 68 | let uniqueObj1 = [ 69 | ...new Map(arrObj.map((item) => [item["name"], item])).values(), 70 | ]; 71 | 72 | // good with reduce 73 | let uniqueObj2 = [ 74 | arrObj 75 | .sort((a, b) => a.age - b.age) 76 | .reduce((acc, val) => ({ ...acc, [val.name]: val }), {}), 77 | ]; 78 | 79 | // groupBy --> age 80 | let aged = []; 81 | let colored = {}; 82 | 83 | arrObj 84 | .sort((a, b) => a.age - b.age) 85 | .map((item) => { 86 | if (item.age === colored) { 87 | // console.log('hast'); 88 | return; 89 | } else { 90 | aged.push(item); 91 | colored = item.age; 92 | } 93 | }); 94 | 95 | // groupBy --> name 96 | let named = []; 97 | let flags = {}; 98 | 99 | for (var i = 0; i < arrObj.length; i++) { 100 | let name = arrObj[i].name; 101 | let obj = arrObj[i]; 102 | 103 | if (flags[name]) continue; 104 | else { 105 | named.push(obj); 106 | flags[name] = true; 107 | } 108 | } 109 | 110 | console.log(named); 111 | -------------------------------------------------------------------------------- /mock api vs real api.txt: -------------------------------------------------------------------------------- 1 | In the context of React testing, the terms "mock API" and "real API" refer to different approaches for simulating and interacting with APIs during the testing process. Let's explore the differences between them: 2 | 3 | Mock API: 4 | 5 | A mock API is a simulated version of an actual API that is used during testing to mimic the behavior of real API requests and responses. Mock APIs are often used to isolate components and ensure that tests focus on specific functionality without being affected by external factors like network connectivity or actual API responses. 6 | 7 | Advantages of using a mock API: 8 | 9 | Isolation: Mock APIs allow you to isolate components and test specific scenarios without making actual network requests. 10 | 11 | Predictable Responses: You can define exactly how the mock API should respond, making it easier to test different scenarios, edge cases, and error conditions. 12 | 13 | Speed: Tests using mock APIs are generally faster because they don't involve actual network communication. 14 | 15 | Stability: Your tests remain stable even if the real API undergoes changes or downtime. 16 | 17 | Real API: 18 | 19 | A real API refers to the actual API endpoints that your application interacts with in production. Testing with a real API involves making actual network requests and receiving genuine responses from the API. 20 | 21 | Advantages of using a real API: 22 | 23 | Realistic Testing: Testing with a real API provides a more accurate representation of how your application will behave in a production environment. 24 | 25 | Integration Testing: Real API testing is especially useful for integration tests that verify how different parts of your application work together. 26 | 27 | Identifying Issues: Real API testing can help you identify issues related to network connectivity, server-side changes, and other external factors. 28 | 29 | End-to-End Testing: Real API testing is essential for end-to-end tests that cover the entire flow of your application, from user interactions to server responses. 30 | 31 | Choosing Between Mock API and Real API Testing: 32 | 33 | The choice between using a mock API and testing with a real API depends on the specific goals of your tests and the context of your application: 34 | 35 | Unit Testing: Mock APIs are commonly used for unit tests to isolate components and their interactions. This approach allows you to focus on the behavior of individual components without relying on external services. 36 | 37 | Integration Testing: When testing how different parts of your application integrate with each other, you might opt for real API testing to ensure a realistic representation of your application's behavior. 38 | 39 | End-to-End Testing: For end-to-end tests that cover the entire user journey, including the communication with the backend, using a real API is essential to validate the full functionality. 40 | 41 | In practice, it's common to use a combination of both mock APIs and real APIs in your testing strategy. Mock APIs are great for unit testing and isolated scenarios, while real APIs are necessary for integration and end-to-end testing to ensure comprehensive test coverage. 42 | -------------------------------------------------------------------------------- /Javascript/checkBoxburgerIcon.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | checkbox 8 | 9 | 10 | 87 | 88 | 89 |
90 |

customize checkbox input & burger icon

91 |
92 | 93 |
94 |
95 | 96 | 97 |
98 | 99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 | 108 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /React-Tutorials-main/README.md: -------------------------------------------------------------------------------- 1 | This repository contains code of react tutorials of my youtube videos. 2 | 3 | You can visit this videos using below links: 😊 4 | 5 | Learn More About, 6 | 7 | ### Forms in React: 8 | https://youtu.be/rNVspUBX3DI 9 | 10 | ### Event Handling in React JS: 11 | https://youtu.be/g_N17GCjnkA 12 | 13 | ### Lifecycle Methods in React JS: 14 | https://youtu.be/Q92WWJt2wsk 15 | 16 | ### Props in React: 17 | https://youtu.be/aHn-MCPfy_U 18 | 19 | ### Higher-Order Component (HOC) in React: 20 | https://youtu.be/kdaqsbEu0bQ 21 | 22 | ### Error Handling in React JS: 23 | https://youtu.be/oR85MugU2cc 24 | 25 | ### Pure Components in React JS: 26 | https://youtu.be/xCZHcuuHGco 27 | 28 | ### Refs in React: 29 | https://youtu.be/ZjIAOfDtVnQ 30 | 31 | ### Build Weather App in React Using React Hooks: 32 | https://youtu.be/uZGhTYZ6eys 33 | 34 | ### Build a Rich text Editor in React 35 | https://youtu.be/PDdZB83_Nrs 36 | 37 | ### React Advanced Topic Playlist: 38 | https://www.youtube.com/playlist?list=PLjxZxD6BDkeZoRU6v7gMyQ7BirGD6u0Lt 39 | 40 | 41 | 42 | 43 | 44 | In the project directory, you can run: 45 | 46 | ### `npm start` 47 | 48 | Runs the app in the development mode.
49 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 50 | 51 | The page will reload if you make edits.
52 | You will also see any lint errors in the console. 53 | 54 | ### `npm test` 55 | 56 | Launches the test runner in the interactive watch mode.
57 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 58 | 59 | ### `npm run build` 60 | 61 | Builds the app for production to the `build` folder.
62 | It correctly bundles React in production mode and optimizes the build for the best performance. 63 | 64 | The build is minified and the filenames include the hashes.
65 | Your app is ready to be deployed! 66 | 67 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 68 | 69 | ### `npm run eject` 70 | 71 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 72 | 73 | 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. 74 | 75 | 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. 76 | 77 | 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. 78 | 79 | ## Learn More 80 | 81 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 82 | 83 | To learn React, check out the [React documentation](https://reactjs.org/). 84 | 85 | ### Code Splitting 86 | 87 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 88 | 89 | ### Analyzing the Bundle Size 90 | 91 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 92 | 93 | ### Making a Progressive Web App 94 | 95 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 96 | 97 | ### Advanced Configuration 98 | 99 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 100 | 101 | ### Deployment 102 | 103 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 104 | 105 | ### `npm run build` fails to minify 106 | 107 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 108 | -------------------------------------------------------------------------------- /React-Tutorials-main/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.0/8 are considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl, { 104 | headers: { 'Service-Worker': 'script' }, 105 | }) 106 | .then(response => { 107 | // Ensure service worker exists, and that we really are getting a JS file. 108 | const contentType = response.headers.get('content-type'); 109 | if ( 110 | response.status === 404 || 111 | (contentType != null && contentType.indexOf('javascript') === -1) 112 | ) { 113 | // No service worker found. Probably a different app. Reload the page. 114 | navigator.serviceWorker.ready.then(registration => { 115 | registration.unregister().then(() => { 116 | window.location.reload(); 117 | }); 118 | }); 119 | } else { 120 | // Service worker found. Proceed as normal. 121 | registerValidSW(swUrl, config); 122 | } 123 | }) 124 | .catch(() => { 125 | console.log( 126 | 'No internet connection found. App is running in offline mode.' 127 | ); 128 | }); 129 | } 130 | 131 | export function unregister() { 132 | if ('serviceWorker' in navigator) { 133 | navigator.serviceWorker.ready 134 | .then(registration => { 135 | registration.unregister(); 136 | }) 137 | .catch(error => { 138 | console.error(error.message); 139 | }); 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /task-doc.md: -------------------------------------------------------------------------------- 1 | this doc is belong to reza sarari 2 | 3 | Total time spent on the project: `24h 10m` 4 | 5 | ## TOC 6 | 7 | 1. [How to run the project](#How-to-run-the-project) 8 | 2. [Task Definition](#Task-Definition) 9 | 3. [Evaluation Criteria](#Evaluation-Criteria) 10 | 4. [My Stack of choice](#My-Stack-of-choice) 11 | 5. [Design Decisions](#Design-Decisions) 12 | 6. [Performance](#Performance) 13 | 7. [Improvement Opportunities](#Improvement-Opportunities) 14 | 15 | ## How to run the project 16 | 17 | 1. Install dependencies 18 | - `pnpm install` 19 | 2. Run project in dev mode 20 | - `npm run start` 21 | 22 | ### 🧪 Running tests 23 | 24 | `npm run test` 25 | 26 | ### 📊 Analyze bundle size 27 | 28 | `npm run analyze` 29 | 30 | ## Task Definition 31 | 32 | ### Objective: 33 | 34 | > Create a Single Page Application (SPA) that showcases your React skills, particularly in hooks, life-cycles, state management, Webpack optimization, and web performance. 35 | 36 | - 👉 Pages: it should contain 3 pages. 37 | - Home 38 | - ✅ The Home page should showcase some dynamic content fetched from an API 39 | like JSONPlaceholder, where users should be able to add, delete, and list items 40 | (e.g., tasks, notes, etc.). 41 | 42 | - User List Page 43 | - ✅ Display a list of users with the following columns: Name, Email, Age, and Actions. 44 | - ✅ Pagination: Limit to 10 users per page. 45 | - ✅ Sort: Provide sorting options for Name and Age. 46 | - ✅ Search: Include a search bar to search users by name. 47 | - User Details Page. 48 | - ✅ Display detailed information of a selected user: Full Name, Email, Age,Address, and Profile Picture. 49 | - ✅ Provide a back button to return to the user list page. 50 | - 👉 Typescript 51 | - ✅ Ensure the entire application is written using TypeScript. 52 | - ✅ Utilize strong typing, including interfaces and types wherever necessary. 53 | - ✅ Implement utility and generic types where appropriate. 54 | - 👉 React Features 55 | 56 | - ✅ Use React hooks effectively (useState, useEffect, useMemo, etc.). 57 | - ✅ Demonstrate side effects handling with useEffect. 58 | - ✅ Use React Router for navigation. 59 | - ✅ Add animations/transitions when navigating between pages 60 | 61 | - 👉 State Management: 62 | - ✅ Choose a state management strategy or tool (e.g., Context API, Redux, Recoil). 63 | Implement a theme switcher (light/dark mode) using the chosen state 64 | management tool. 65 | - 👉 Performance: 66 | 67 | - ✅ Implement code-splitting using React.lazy() and Suspense. 68 | - ✅ Use useMemo or useCallback where necessary to showcase your ability to 69 | prevent unnecessary renders or recalculations. 70 | - ✅ Ensure no render-blocking resources are present. 71 | - ✅ Optimize images or any assets you use. 72 | 73 | - 👉 Webpack: 74 | 75 | - ✅ Customize the Webpack config (You might start with Create React App but eject 76 | it for customization). 77 | - ✅ Ensure the final bundle is optimized in size. 78 | - ✅ Implement tree-shaking if necessary. 79 | - ✅ Set up Webpack to show a bundle size report. 80 | - ❌ Server-Side Rendering (Optional but a plus): 81 | - ❌ Implement server-side rendering for the application to showcase initial load 82 | performance enhancement. 83 | 84 | - 👉 Extras: 85 | 86 | - ✅ Use styled-components or any CSS-in-JS solution of your choice. 87 | - ✅ Ensure the application is responsive. 88 | - ✅ Implement error boundaries in the application for better error handling. 89 | 90 | - 👉 Documentation: 91 | 92 | - ✅ Include a README.md detailing how to run and build the project, and any design 93 | decisions you made. 94 | - ✅ Discuss how you ensured the application's performance and any tools or 95 | techniques you used. 96 | 97 | - 👉 Bonus 98 | - ✅ Test: Quality and coverage of unit tests 99 | - only Button and Image component have tests 100 | 101 | ## Evaluation Criteria 102 | 103 | 1. Code Quality: Consistent code style, clear namings, modularity, and usage of best 104 | practices. 105 | 2. Functionality: All features should work without errors. 106 | 3. Performance: No unnecessary re-renders, efficient data fetching, and optimized asset 107 | loading. 108 | 4. Responsiveness: The application should be fully responsive across devices 109 | 110 | ## My Stack of choice 111 | 112 | - Typescript 113 | - Webpack 114 | - Babel 115 | - React 116 | - Styled-Components 117 | - Zustand 118 | 119 | ## 🔨 Design Decisions 120 | 121 | ### 🔶 About Dark Mode Implementation 122 | 123 | What is really missing in this puzzle of choices is that the task describe that the dark mode should be applied using the state manager. although what I did is using both the state manager and styled components capabilities. in the mean time the more simple process is just use the `matchMedia` browser API. 124 | 125 | we could just add themes like this 126 | 127 | ```css 128 | [data-theme="light"] { 129 | --color-bg: #ffffff; 130 | --color-fg: #000000; 131 | } 132 | 133 | [data-theme="dark"] { 134 | --color-bg: #000000; 135 | --color-fg: #ffffff; 136 | } 137 | ``` 138 | 139 | and then change the property in our HTML tag 140 | 141 | ```html 142 | 143 | ``` 144 | 145 | and if we needed to check the theme in JS we can just use 146 | 147 | ```js 148 | const systemSettingDark = window.matchMedia("(prefers-color-scheme: dark)"); 149 | ``` 150 | 151 | and use localStorage to save the preferred theme. 152 | 153 | either way its just a design choice and both implementations works accurately. 154 | 155 | ### 🔶 Why PocketBase 156 | 157 | PocketBase is a self-hosted solution that help create SASS application very fast and easy. in this project we needed something to be able to perform CRUD operations and third-party tools such as JSONPlaceHolder has their limits. such as not allowing to perform many activities in a certain time stamp. 158 | 159 | I had previous experience with PocketBase for one of my own projects and I thought that it might help here. and no surprise. it did a lot. I got a free fly.io server and boot up a docker image and set volumes for data consistency and after just 10 minutes I have a fully working backend for my project with no cost. 160 | 161 | I had experiences with other Headless CMS ( PocketBase is not a headless CMS ) such as Contentful and Strapi. but I thing it's a total overkill to use a CMS for this app. 162 | 163 | ### 🔶 Why not Axios ( Or similar HTTP libraries ) 164 | 165 | I strongly believe in 99.99% percent of projects you don't need such things to handle your HTTP request. such as I did in this project you can simply wrap the fetch in a function and customize it as much as you want. I implement this method in both [Legamart](https://legamart.com) and [Postpace](https://postpace.io) and both working perfectly. 166 | 167 | ### 🔶 Why Zustand 168 | 169 | 1. **Simplicity**: Zustand provides a simple and straightforward API based on React hooks, making it easy to learn and use, especially for developers already familiar with React hooks. 170 | 2. **Lightweight**: Zustand is a small library with a minimal overhead, which can result in better performance compared to larger state management solutions like Redux. 171 | 3. **Easy Integration**: Since Zustand is built around hooks, it seamlessly integrates with React components without requiring extra dependencies or boilerplate code. 172 | 4. **No Boilerplate**: Zustand reduces the need for boilerplate code, as it allows you to define your state and update functions with minimal setup. 173 | 5. **Centralized State**: Like Redux, Zustand also offers centralized state management, which can help to keep your application's state organized and manageable. 174 | 6. **Performance**: Zustand is designed to be lightweight and efficient. It does not introduce unnecessary abstractions or middleware layers, which can result in better overall performance compared to more complex state management solutions like Redux. 175 | 7. **Immutability**: Zustand leverages Immer under the hood, which allows you to directly mutate the state in a mutable manner. However, Immer ensures that these mutations are made in an immutable way behind the scenes. This makes it easier to work with state updates and helps prevent accidental state mutations. 176 | 8. **TypeScript Support**: Zustand has excellent TypeScript support out of the box. Its API is well-typed, which can help catch type-related errors during development and improve code quality. 177 | 9. **Support for React Concurrent Mode**: Zustand is designed to work well with React Concurrent Mode (a.k.a. React Suspense). This allows us to take advantage of React's concurrent rendering capabilities without additional adjustments. 178 | 10. **Small Bundle Size**: Due to its simplicity and focused feature set, Zustand contributes to smaller bundle sizes, which is essential for optimizing application performance. 179 | 180 | ## Performance 181 | 182 | 1. Using debounce to reduce the api calls to the server 183 | 2. Using useMemo to prevent rerendering lists that does not need to rerender 184 | 3. Customizing image component and use lazy loading and also forcing the width and height to prevent any CLS 185 | 4. Not using unnecessary third-party tools such as axios or lodash to reduce the overhead 186 | 187 | ## 🔥 Improvement Opportunities 188 | 189 | 1. Use Linting tools to prevent code mistakes and help new joiners match the code style. 190 | 2. We can use Cloudflare image optimization for our image component so we can optimize, resize, decode image on demand. and also we can use implement a backend and use Sharp to optimize images. 191 | 3. Adding loading state for table for a better UI 192 | 4. Implement Picture implementation for image component and use the responsive methods for images instead of reducing the width ( it can easily be done after cloudflare optimization) 193 | --------------------------------------------------------------------------------