Make files like .gitignore & choose ES-6 syntax.type : module. Cut Readme file.
To run react server . Use command
npm run react-dev
# Rules
Create-react-app
we can import relatively only inside src directory.
Fundamentals
rfce by typing this in component file , we can get template of component.
Variables inside component always enclosed in {}.
Component file name be in either .jsx or .js format.
We are not using CDN's here, instead we are using npm packages & external webpack.
Only 0, false, null ,"" , undefined are considered as false.
Imagine DOM as a tree like structure. In this structure if we define state in some component. Then if we have to use it in upper level components, then we have to drill the state to all the way to up.
To get rid of this , we define state outside the component in seprate file.
Components & props & Events
A component name always in capital letters.
Components are nothing but regular javascript functions that returns jsx .
Jsx is always enclosed in parenthesis () .
Inside JSX we cannot use if-else. But we can use {condition ? truthy : falsy} or {condition1 && condition2 ...} or {condition1 || condition2 ...}
As conditions are all about uncertainity , so these are enclosed in {}.
If multiple statements are true , then && returns last truthy statement. And || returns first truthy staement.
props.children is used to fetch children elements passed between parents.
Useful functions
// map, slice , unshift , forEach , copy operator.// 1. ()=> { } , Always enclose in curly braces if there is no single linearray.forEach((element)=>{total+=Number(element.amount);if(element.amount>=0)profit+=Number(element.amount);elseloss+=Number(element.amount);});// 2. Events used with forms// onSubmit// onChange with input// // Map function{blogs.map((element,index)=>())}
Components stylings
For css files to work , we need loaders.css-loaders && style-loader
CSS Modules are used to style components, which are named as fileName.module.css.
In css modules styles are written in form of classes only.
// This way you can include ,multiple classes at once....<pid="money-plus"className={`${styles.money}${styles.plus}`}>
Hooks
1. useState()
If we have to change only 1 property in state. We first have to copy the prevState using [...operator]
If we are using setState , we dont have to manually render the component again.
All side-effects are performed in this. like fetching data from API, calling DOM methods , etc.
For each different task, we can use different useEffect() .
only setup function will be executed component is maded & every time component updates.
setup function + empty array ,executed once only when component is maded.
setup function + array with element , executed when component is maded + everytime when change occur in element.
if there is return statement in setup function , that will be executed when component is destroyed.
import{useEffect}from'react';useEffect(setup,dependencies);<!--FetchingdatafromAPI-->useEffect(()=>{fetch("https://api.example.com/data").then((response)=>response.json()).then((data)=>setData(data));},[]);<!--CallingSideEffects-->useEffect(()=>{consttimer=setInterval(()=>{console.log("Timer running");},1000);// Cleanup function to clear the interval when the component unmountsreturn()=>clearInterval(timer);},[]);<!--LocalStorageuses-->useEffect(()=>{constemail=localStorage.getItem("email");if(email){setEmail(email);}},[]);useEffect(()=>{localStorage.setItem("email",email);},[email]);
4. useReducer()
If we are manipulating states using useState in too many event-handlers or functions. Than we can use this hook.
reducer is a function made outside our component which contains manipulation of state logic.
Then provide the context. Create context will return 2 values consumer & provider
Consume the context.
import{createContext,useContext}from"react";// 1. Created a contextexportconstcustomContext=createContext();exportfunctionCustomItemContext(props){<!--Setallstateshere&usethemherethatismanipulatethemhere--><!--Aftermakingandmanipulatingallstateswereturninend--><!--2.Providecontext-->return(<customContext.Providervalue={{total,items,handleAdd,handleRemove,reset,toggleCart,cart,clear}}>{showCart&&<CartModal/>}{children}</customContext.Provider>);}<!--3.Usethatcontext-->exportfunctionuseValue(){constvalue=useContext(customContext);returnvalue;}<!--4.Howtouseincomponents--><CustomItemContext><Navbar/><Items/></CustomItemContext><!--5.TheninNavbar&Items,wecansimplyfetchstateslikethis-->functionNavbar(){const{total,items,reset,toggleCart}=useValue();}
Routing
Routing provides different URL addresses in SPA without a new page.
Redux
Events
Events are written in tags as attributes. eg. <button onClick = {}> </button>. These can be called in 2 ways.