Skip to content

Instantly share code, notes, and snippets.

@subrotoice
Last active May 20, 2024 15:30
Show Gist options
  • Save subrotoice/98eb2fcbcef23c733cd36e0575c2e37c to your computer and use it in GitHub Desktop.
Save subrotoice/98eb2fcbcef23c733cd36e0575c2e37c to your computer and use it in GitHub Desktop.
Tutorial: https://www.w3schools.com/react/default.asp
ReactJs: https://www.youtube.com/playlist?list=PLtLCBrFxFR-f9HJo1AEwca7Db9U_0-iHv (My Playlist)
https://www.udemy.com/course/react-tutorial-and-projects-course
Mosh: codewithmosh.com/courses/ultimate-react-part1
React-Basic GitHub: github.com/subrotoice/react-basic
Deploy Netlify: youtube.com/watch?v=tVzpC5_AC8M
Why Should use React: https://prnt.sc/opwGtKUm3jzg
✅ JavaScript for React
# Javascript Array[], Object{}
const cars = ["Saab", "Volvo", "BMW"]; // Array [square brackets]
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; // Object {curly braces}
JSON.parse(); // For converting JSON strings --> JavaScript objects
JSON.stringify(); // For converting an object --> a JSON string ( Plain string: {"firstName":"John","lastName":"Doe","age":50} )
const person = {
name: "Subroto",
location: "Kushtia",
}
localStorage.setItem("person1", JSON.stringify(person)); // Output: {"name":"Subroto","location":"Kushtia"}, JS object ke JSON data te convert kore
let person1 = JSON.parse(localStorage.getItem('person1') ) // JSON -> JS Object using Local Storeage
JSON is to exchange data to/from a web server. Data from a web server is always a string. JSON.parse(): data becomes a JavaScript object.
//Output:
{
name: "Subroto",
location: "Kushtia",
}
You can access a JavaScript object like this:
person.name; or person["name"]; // It can also be accessed like this
# Spread operator (...): copy all or part of an existing array or object into another array or object.
const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo]; // numbersCombined = [...numbersOne, singleElement] // 2nd item is not array
document.write(numbersCombined);
let dataObj = {name:'Subroto', dept:'ICT', dist:'Kushtia'} // Object always Curly brackets {}; Don't use const type here
dataObj = {...dataObj, name:'kamal'} // Output: {name:'Kamal', dept:'ICT', dist:'Kushtia'}
const name = "BD"; // Example 1
const person = { name: "John", age: 30, city: "New York" };
const clonePerson = { ...person, name }; // {name: 'BD', age: 30, city: 'New York'}
const address = "India"; // Example 2
const person = { name: "John", age: 30, city: "New York" };
const clonePerson = { ...person, address }; // {name: 'John', age: 30, city: 'New York', address: 'India'}
# Var, Let, Const -------------ES6------
var: function scope, not a block scope. Can be updated and re-declared in scope
let: block scope. bounded by {}, can be updated but cannot be re-declared in scope
let a = 10
let a = 10 // It is not allowed
a = 10 // It is allowed
const: block scope, maintain constant values. can't be updated or re-declared in scope
# Class --------------
class Car {
constructor(name) {
this.brand = name;
}
}
const mycar = new Car("Ford");
document.write(mycar.brand); // Outpur: Ford
class Car {
constructor(name) {
this.brand = name;
}
present() {
return 'I have a ' + this.brand;
}
}
const mycar = new Car("Ford");
document.write(mycar.present()); // Output: I have a Ford
# Arrow Function--------------------
function square(number) { // Regular function
return number * number;
}
Conciseness: Arrow functions are more concise, especially when the function body is a single expression.
If the body is more than one line or requires multiple statements, you can use curly braces {} and include a return statement.
const square = function(number) { return number*number; } // Regular function same as before
const square = (number) => {return number*number } // with arrow function; function keyword gone, seems like this goes to that
const square = number => { return number*number; } // Single Parameter
const square = () => {return number*number;} // No Parameter; With one statement, and the statement returns a value, you can remove the brackets and the return keyword
const square = number => number*number; // If one statement; read as number goes to number square; Arrow Functions Return Value by Default
console.log(square(4)); // output: 16; Function Call
const filtered = [12, 5, 8, 130, 44].filter((value) => value > 50); // here value is arg, return value>50
const filtered = [12, 5, 8, 130, 44].filter((value) => {return value > 50;});
const filtered = [12, 5, 8, 130, 44].filter((value) => {value > 50}); // Error, if use {} then must need to give return; function must have a return value eight explecit or implecit (one statement)
# Event -- Web app human er sathe interact kore
onClick = {changeName} // Where there is an event there is an eventHandelar function. You can do anything with this function
# Filter Array ----------------
array.filter(function()) // each iteration pass an element and if function return true that element keep in filtering
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6); // Who follow condition remain here; arror function(loop iterate for every array item)
console.log(result); // Expected output: Array ["exuberant", "destruction", "present"]
let cities = [
{name: 'Los Angeles', population: 3792621},
{name: 'New York', population: 8175133},
{name: 'Chicago', population: 2695598},
{name: 'Houston', population: 2099451},
{name: 'Philadelphia', population: 1526006}
];
const bigCities = cities.filter((city) => city.population > 3000000); // arrow function
let bigCities = cities.filter(function (e) { // regular function
return e.population > 3000000;
});
setTodos(todos.filter((e)=>{ // In Todo App, https://github.com/subrotoice/todos/blob/master/src/App.js#L17 //arrow function
return e!==todo;
}))
todos.filter((e) => e !== todo) // here is also return in implicitly. default return for one statement
const newTodos = todos.filter((e) => e !== todo);// Same upper code in two line. If not want to keep in another variable then use return
setTodos(newTodos);
# Map - Creates a new array from calling a function for every array element
const array1 = [1, 4, 9, 16];
const map1 = array1.map((x) => x * 2);
console.log(map1); // Expected output: Array [2, 8, 18, 32]
{items.map((item) => { // Not save to other array just give output with return
return <pre>{JSON.stringify(item)}</pre>;
})}
# Reduce()--- Callback function's return value will be the accumulator of next iteration what ever the return value we set.
array.reduce(callbackFn, initialValue)
array.reduce(function(total, currentValue, currentIndex*, arr*), initialValue*) // * optional, On the first call, total is initialValue if the latter is specified; otherwise its value is array[0] in that case 5 ta element thakle 4 bar itaration hobe.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
); // currentValue oi iteration er value
console.log(sumWithInitial); // Expected output: 10
{expenses.reduce((acc, expense) => acc + expense.amount, 0)} // expense{id:1, description:"aaa", amount: 10}
# import/export -------
Named exports: are constructed using curly braces. Default: exports are not
https://prnt.sc/Ck-jB_DR7v_r
const name = "Jesse 33"; // in person.js
const age = 40;
export { name, age };
const message = () => { // in message.js
const name = "Jesse";
const age = 40;
return name + " is " + age + "years old.";
};
export default message;
<script type="module">
import message from "./message.js";
import { name, age } from "./person.js";
console.log(message());
console.log(name);
</script>
Modules: only work with the HTTP(s) protocol. A web-page opened via the file:// protocol cannot use import / export.
React Js-- Import/Export
import "bootstrap/dist/css/bootstrap.css"; // node_modules import
import "./index.css"; // Direct File import
import Form from "./components/Form"; // Module Import
import { useState } from "react"; // Module Destructring Import
import { BsFillCalendarFill } from "react-icons/bs"; // Module Destructring Import
✅ React JS fundamentals ~~~
# ReactJS-----Project Start-------
nodejs.org -> npx create-react-app subroto-react-app -> cd my-react-app -> npm start
(Using Vite) npm create vite@4.1.0 -> cd game-hub -> npm install -> npm run dev; or, npm create vite@latest
git init -> git add . -> git commit -m "Initial Commit" // good practice keep repo, not medetoryly keep in github
git remote add origin https://github.com/subrotoice/game-hub.git
git push -u origin master
# JSX | To write HTML code in JavaScript. Allow direct HTML in js(they are not HTML but JS Object)
// HTML lekhar jonno kono tension nay just write code. JS asle {}. Js er modde abar no tension HTML er modde abar JS asle {} (Deep Thinking)
const myElement = <h1>I Love JSX!</h1>; || <h1>{2+3}</h1> // Output: 6
ReactDOM.render(myElement, document.getElementById('root'));
# Inside JSX anywher you place variable/expresssion in HTML tag you need to use { }
{ cities.map( (city) => (<h1>{city.name}</h1>) ) }
{categories.map((category) => (
<option value={category}>{category}</option> // { category }
))}
Virtual DOM: https://prnt.sc/dP3lF6zUg8A2
# Component(Part of Something): 1. Functional(JavaScript) top 2. Markup(in return) bottom section. MUST PascalCase use Component
function App() { // Functional Component. To Use: <Hello />, Passing Value: <Car brand="Ford" />
const [responseType, setResponseType] = useState("posts"); // Two section. 1. Functional Section(Javascript) Top, 2. Markup Section bottom
console.log("Component Render");
useEffect(() => {
console.log("useEffect Run");
}, [responseType]);
return (
<h1>Hello World! 22 66</h1>
);
}
return (
<div> // If more line then it should be another element, div or span. Otherwise Error
<h1>Hello World! 22 66</h1>
<h1>Hello World! 44 88</h1>
</div>
);
# Props are arguments passed into Components, JS Object ie. props.name, props.email
React Props are like function arguments in JavaScript and attributes in HTML.
<Car brand="Ford" />
function Car(props) { // props are user define name ie. subroto| U can use: function Car({brand}) leater on you can uses {brand} in stade of {props.brand} its called destructuring
return <h2>I am a { props.brand }!</h2>; // evabe mone kora lagbe: brand variable function e o ase just props.brand use korte hobe
}
<Student name="Subroto" email="subroto@gmail.com" other={{address: "Kushtia", mobile: "222"}} />
<div>
<h1>Hello {props.name}</h1>
<h1>Email: {props.email}</h1>
<h4>Email: {props.other.address}</h4>
</div>
// Passing function as props, Functions are used to notify the parent (consumer) of a component about certain events that occur in the component, such as an item being clicked or selected.
function getData() { // app.js
alert("Alert from App");
}
return (
<div className="App">
<Student data={getData} />
</div>
);
<button onClick={props.data}>Click Me</button> // Student.js
// Props Choldren
<Student>Hello World2</Student> // App.js, Inside component tag
<button onClick={props.data}>{props.children}</button> // Student.js
NB: When the state or props of a component change, React will re-render the component and update the DOM accordingly.
# Condition --- Conditional Rendering--------
{user==1?<h1>Line1 User1</h1>:<h1>Line1 User2</h1>} <br /> // 2 options
{user==1?<h1>User1</h1>:user==2?<h1>User2</h1>:<h1>User3</h1>} // More then 2 options
Short Cirtuit Evolution(Conditiona Rendering) https://prnt.sc/qaF612dRcm8c
// When you don’t need the else branch, you can also use a shorter logical && syntax:
<div>
{isLoggedIn && <AdminPanel />}
</div>
# Map Array---Loop--Convert One array to Another array---Arraw function as CallBack-----VVI----
const myArray = ['apple', 'banana', 'orange'];
const myList = myArray.map((item) => <p>{item}</p>)
// Array of Object (Array er modde Object ache)
let todos = [
{
sno : 1,
title : "Go To Home",
desc : "Home tour of your favorite think to do"
},
{
sno : 2,
title : "Go To Office", // to accesss: todos[2].title (1st e array number, then object notetion )
desc : "Office tour of your favorite think to do"
},
{
sno : 3,
title : "Go To Park",
desc : "Park tour of your favorite think to do"
}
]
{props.todos[0].title} // Output: Go To Home
{props.todos.map((item) => <TodoSingle todo={item} />)} // in TodoSingle: <h1>{props.todo.title}</h1> // Print all Title
{ nan.map( (item) => <>{item}</> ) } // must enclose with <> </> otherwise not work| So inside map: (item) => <>{item}</>
const myList = myArray.map((subro) => <p>{subro}</p>) // Loop na use kore array manipulation, const myArray = ['apple', 'banana', 'orange'];
{cars.map((subro) => <Car brand={subro} />)}
Map function may return: https://prnt.sc/bKhcscGlbISx
# Hook, like static variable in C, Start with "use", useState, useEffect hook name | youtube.com/watch?v=p7wZ_4sWZ4s
# useState Hook
function App() { // State: A Component’s Memory, Synchronizing with Effects
const [data, setData] =useState("Kamal"); // ex2: const [data, setData] = useState(0); const [items, setItems] = useState([]); type must defien like it will take array. Otherwise Error
function updateData() {
setData("Subroto"); // To update variable | ex2: setData(data+1);
// data = "Subroto"; // Not Allwo Here
}
return (
<div className="App">
<h1>{data}</h1>
<button onClick={updateData}>Update</button> // onClick={()=>updateData()} arrow funciton, cannot use onClick={updateData()}
</div> // <button onClick={()=>setName("Subroto")}>Update</button> // Inline
);
}
const [firsName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
// It's better to group related state variable inside an object
const [person, setPerson]=useState({
firsName: '',
lastName: ''
});
NB: state এমন ভেরিয়েবল রাখতে হবে যার ভ্যালু নিয়মিত চেঞ্জ হয়ে এবং চেঞ্জ হলে re-render দরকার (Skep Unnecessary Rendering), Here First name and Last name calculation kore pawa jay, Fullname rakhar dorkar nai calculation kore pawa jai
# **Updating Object State**
const [drink, setDrink] = useState({
title: "Ram",
price: 5,
});
const handelClick = () => {
// System 1
const newDrink = {
title: "Ram",
price: 6,
};
// System 2: Spread ... operator Making new object so { }, Copy all property of an object and change(because same poperty) some part, it my be combine if new poperty, same for Array
const newDrink = {
...drink,
price: 8,
};
setDrink(newDrink);
// System 3: Best
setDrink({ ...drink, price: 9 });
};
// Updating Nested Object
const [drink, setDrink] = useState({
title: "Ram",
price: 5,
alcoholBottol: {
nip: 250,
pide: 500,
full: 750,
},
});
const handelClick = () => {
setDrink({ ...drink, alcoholBottol: { ...drink.alcoholBottol, full: 1000 } });
};
# **Updating Array**
const [mod, setMood] = useState(["Happy", "Angry"]);
const handelClick = () => {
// Add
setMood([...mod, "Joy"]);
// Delete
setMood(mod.filter((mod) => mod !== "Happy"));
// Update
setMood(mod.map((mod) => (mod === "Happy" ? "Happyness" : mod)));
};
# afterRender should be the name. Execute after completing component rendering
useEffect(() => { // useEffect Hooks
console.log("Count: " + count)
}, [count]); // 1st argument function, 2nd argument condition(count state change hole eta kaj korbe, kichu na dile je kono state va props change holei kaj korbe)
# useEffect Hook---Used to talk to outside world---Every time your component renders, React will update the screen and then run the code inside useEffect.
In other words, useEffect “delays” a piece of code from running until that render is reflected on the screen.
function MyComponent() {
useEffect(() => {
// Code here will run after *every* render
});
}
// Fetching data using fetch api and useEffect
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/users`)
.then((response) => response.json())
.then((json) => setItems(json));
}, [responseType]);
useEffect(() => {
//Runs on every render
});
useEffect(() => {
//Runs only on the first render
}, []);
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);
NB: State value change hole full component rerender hoy. useEffect o rerender hoy but last e.
- Irrespective of anything, ek bar useEffect render hobei, [empty] hole ar na, [state] state change hole
In short amara useEffect ke state change er upor depend kore rerender korate parbo.
Watch: youtube.com/watch?v=0ZJgIjIuY7U
# Hide/Show/Toggle -----Content-----
function App() {
const [show, setShow] = useState(true)
return (
<div className="App">
{
show ? <h1>Hello World !</h1> : null
}
{/* <button onClick={()=>setShow(true)} >Show</button>
<button onClick={()=>setShow(false)} >Hide</button> */}
<button onClick={() => setShow(!show)} >Toggle</button>
</div>
);
}
# Form--Input---
function App() { // onChange Effect Input
const [data, setData] = useState(null);
const [print, setPrint] = useState(false);
function getData(val) {
console.log(val.target.value);
setData(val.target.value);
setPrint(false);
}
return (
<div className="App">
{print?
<h1>{data}</h1>
:null
}
<input type="text" onChange={getData} />
<button onClick={()=>setPrint(true)}>Show Data</button>
</div>
);
}
Ex2: ---
function App() {
function getFormData(e) { // e is user Defined
e.preventDefault();
console.log(name, car, confirmation);
}
const [name, setName] = useState("");
const [car, setCar] = useState("");
const [confirmation, setConfirmation] = useState(false);
return (
<div className="App">
<form onSubmit={getFormData}> // Funciton call on onSubmit event
<input type="text" onChange={(evt)=>setName(evt.target.value)} /> <br/>
<select onChange={(e)=>setCar(e.target.value)}>
<option>Select Option</option>
<option value="bmw">BMW</option>
<option value="tata">Tata</option>
</select><br/>
<input type="checkbox" id="confirmed" onChange={(myEvent)=>setConfirmation(myEvent.target.checked) }/><label for="confirmed"> Confirmed</label> <br/>
<button type="Submit">Submit</button>
</form>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment