项目作者: omarbelkady

项目描述 :
Client Side JS
高级语言:
项目地址: git://github.com/omarbelkady/ReactJS.git
创建时间: 2020-09-19T01:04:03Z
项目社区:https://github.com/omarbelkady/ReactJS

开源协议:

下载


FE Lib

Datatypes:

  1. Numbers

  2. Text

  3. Boolean

  4. Consts

  5. Objects

Fragments In React:

  1. <> </>

Prereqs For React JS:

  • HTML
  • CSS
  • JS


HTML Fundamentals

  • Elements
  • Attributes
  • Headings
  • Paragraph
  • Comments ie <! — —>
  • Colors
  • Links
  • Images
  • Classes
  • Favicons
  • ID
  • Tables
  • Iframes
  • Lists
  • Div/Span
  • Input
  • Forms
  • Metatags


CSS Fundamentals

  • Syntax
  • Selectors
  • Borders
  • Padding
  • Margins
  • Fonts
  • Icons
  • Links
  • Display
  • Overflow
  • min/max-width
  • z-index
  • pseudo-class
  • Units
  • !important
  • Text Effects
  • Math Function
  • Transitions
  • Animations
  • 2D/3D
  • Variables
  • Flexbox
  • Masking
  • Media Queries
  • Grid
  • Design System


JS Fundamentals

  • Expressions
  • Lexical Structure
  • Types
  • Variables
  • Math Operator
  • Functions
  • IIFE
  • Arrow Functions
  • Loops
  • Scope
  • Template Literals
  • Semicolons
  • Callbacks i.e. function passed as an arg to another function
  • Strict Mode
  • DOM
  • Variables
  • Async/Await
  • Timers
  • Binding
  • Prototyping
  • Promises
  • Unicode
  • Inheritance
  • RegEx
  • Generators

Cover In This Order [REACT]

  • What Is React

  • Setup Environment

  • JSX

  • Components

  • State

  • Props

  • Lists & Keys

  • Lifecycle Methods

  • Styling

  • Form Handling

  • Data Handling

  • Hooks

  • Custom Hooks

  • Context API

  • Portals

  • Router

  • State Management

  • Patterns

1 How to install prereqs for react and all other dependencies necessary to your project

  1. mkdir my-react-app
  2. cd my-react-app
  3. npm init --y
  4. npm install react react-dom
  5. npm install --save-dev webpack webpack-dev-server html-webpack-plugin @babel/core babel-loader @babel/preset-env @babel/preset-react

2: Create React Application using Vite 2023 method

  1. npm create vite@4.1.0
  2. #Enter (y)
  3. #Give your project a name e.g. 2525lo837765anco
  4. #Select A Frameworks(Van, Vue, R, Preact, Lit, Svelte, etc.)
  5. #Select a variant(JS, TSC, JS+SWC, TSC+SWC)

3: Remove the following 5 files that come shipped with the create-react-app command

  • App.test.js

  • index.css

  • logo.svg

  • serviceWorker.js

  • setupTests.js

4. React Project Layout. If you are build a SPA no need for components dir ignore this step and any subsequent one

  1. ├── README.md
  2. ├── node_modules
  3. ├── package.json
  4. ├── .gitignore ------- list the files you do not want git to track here
  5. ├── public
  6. ├── favicon.ico
  7. ├── index.html ------ to bootstrap your react app import it here
  8. └── manifest.json
  9. └── src
  10. ├── App.css ---------------- styling
  11. ├── App.js ----------------- root component
  12. ├── App.test.js ------------ unit tests
  13. ├── components
  14. ├── Home.jsx
  15. ├── NameOfYourSecondPage.jsx
  16. ├── NameOfYourThirdPage.jsx
  17. ├── NameOfYourFourthPage.jsx
  18. ├── NameOfYourNthPage.jsx
  19. ├── Navigation.jsx
  20. ├── Footer.jsx
  21. ├── index.css
  22. ├── index.js
  23. ├── logo.svg
  24. └── serviceWorker.js

4. React Spring Boot Project Layout

  1. /my-springboot-react-app
  2. |-- /backend
  3. | |-- /src
  4. | | |-- /main
  5. | | | |-- /java
  6. | | | | |-- /com
  7. | | | | |-- /myapp
  8. | | | | |── /controller .....Contains Spring MVC controllers to handle HTTP requests.
  9. | | | | |── /model ..... Defines data models or entities for the application.
  10. | | | | |── /repository ..... Contains Spring Data repositories to interact with the database.
  11. | | | | |── /service ..... Implements business logic and interacts with repositories.
  12. | | | |── /resources
  13. | | | |── /application.properties ..... Configuration file for Spring Boot application properties.
  14. |── /frontend
  15. | |── /public
  16. | | |-- index.html ..... HTML template for the React application.
  17. | |── /src
  18. | | |-- /components ..... Storage for all your React Components
  19. | | |-- App.js ..... Main React component that serves as the entry point of the frontend.
  20. | | |-- index.js ..... Entry point for the React application, where it's connected to the DOM.
  21. |── pom.xml ..... must have Backend (Maven - pom.xml): Maven-based Java projects to define project information, manage project dependencies, and configure various build aspects
  22. |── package.json

Within pom.xml I must have the following dependencies:

  • Spring Boot Starter Web
  • Spring Boot Starter Data JPA
  • H2 Database (or any database of your choice)
  • Spring Boot Starter Test (for testing)

For Projects

5. Create a components folder in your src folder

  1. ├── README.md
  2. ├── node_modules
  3. ├── package.json
  4. ├── .gitignore
  5. ├── public
  6. ├── favicon.ico
  7. ├── index.html
  8. └── manifest.json
  9. └── src
  10. ├── App.css
  11. ├── App.js
  12. ├── App.test.js
  13. └── components
  14. └── Footer
  15. └── Navbar
  16. ├──index.js
  17. ├──
  18. └── images
  19. └── pages
  20. └── videos
  21. ├── index.css
  22. ├── index.js
  23. ├── logo.svg
  24. └── serviceWorker.js

5. React Typescript Project Layout

  1. .
  2. ├── .gitignore
  3. ├── .editorconfig
  4. ├── .env
  5. ├── README.MD
  6. ├── package.json
  7. ├── package-lock.json
  8. ├── tsconfig.json
  9. ├── tslinst.json
  10. ├── public/
  11. ├── index.html
  12. └── loader.css
  13. ├── srcipts/
  14. └── mjml-compile.js
  15. └── src/
  16. ├── assets/
  17. └── logo.svg
  18. ├── components/
  19. └── button/
  20. ├── index.tsx
  21. └── button.specs.ts
  22. ├── middlewares/
  23. └── auth.tsx
  24. ├── pages/
  25. ├── root.tsx
  26. ├── home.tsx
  27. └── login.tsx
  28. ├── routes/
  29. └── index.tsx
  30. ├── services/
  31. └── http.ts
  32. ├── styles/
  33. ├── ant-override.scss
  34. ├── _variables.scss
  35. └── index.scss
  36. ├── utils/
  37. └── index.ts
  38. ├── app.tsx
  39. └── index.tsx

6. If you are a build a MPA run this command to setup routing

  1. npm i react-router-dom

7. Schema hasn’t been registered for model

  • Check your arguments for mongoose.model call

8. Data Fetching From An API Misconception

  • Wrong: Fetch the Data from An API then you render it to the DOM and no render if you haven’t fetched the data

  • True: Fetch the data from A Resource(aka API). When the data comes in, you update the state thanks to the hook and we render the new state to the dom

Useful Resources for the FE

  1. Mozilla Developer
  1. W3 School
  1. CSS Reference For Visual CSS Guides
  1. JS Learning
  1. CSS Tricks … To learn the ins and outs of CSS with some cool tricks
  1. Code Pen …. Super Useful Resource
  1. Useful Snippets for the Front End

Tutorials

  1. HTML5 Rocks
  1. Smashing Magazine
  1. Tuts+
  1. Geeksforgeeks
  1. W3Schools

Quickly Generate An Express App

  1. npx express-generator --no-view api

Cool Libraries to Use

  • AniJS

  • AutoComplete.js : simple pure vanilla js lib for autocompletion

  • Base Web: Ready to use Components

  • Darkmode.js: uses CSS mix-blend mode in order to bring dark mode to your WS

  • FrenchKiss.js: For simple and fast soln to handling internationalization

  • Freezeframe.js: Library that pauses animated gifs and animated them on mouse hover/click/touch

  • HotKeys.js: For capturing keyboard input

  • Indigo Player: xtensible js lib for playing videos

  • Lax.js: for Parallax Effect

  • Lottie JS

  • MOJS

  • Moveable: Draggable, Resizable, Scallable, Rotatable, Wrapable, Pinchable Elements

  • Optimole: Manage and Resize Images depending on how much resources you have

  • Popmotion Pure

  • Rallax.js: VanillaJS plugin to implement parallax scrolling effect

  • React Image Magnifiers: Responsive, image magnifying react component on mouse and touch

  • React Redux Loading Bar: component providing loading bar for long running tasks

  • React Simple Img: React lazy loading images iwth IntersectionObserver API

  • React Toastify: Add Notifications to your React App

  • SceneJS: JS Animation for creating animated Web Sites

  • ScrollReveal JS

  • Simple Keyboard: simple, fast, customizable virtual keyboard

  • Zdog: Walkthrough on how to design, display and animate a design

  • fslightbox: for display various types of sources in a box

Free Hosting Providers

Most Common

Free Website Templates

Cool APIs to work with in React

ReactJs VS. NodeJS

  • ReactJS: UI Library

  • NodeJS: Server Side/Back End ====> API Exposer/Kitchen

  • API: Communicator/Waiter

Roadmap

ReactJS Roadmap

What is onChange Event

  • An onChange Event is when the state/value of anything changes

How Is Data Passed in ReactJS

  • Primitive(by, ch, short, int, long, fl, dou) data types in ReactJS are passed by value as in any other programming language

  • Variables which aren’t primitives are passed by reference aka Arrays, Objects and Functions

Mistakes Commonly Made And How To Fix?

  1. Module Not Found: Cannot Resolve …
  • This means that you are trying to use a file that isn’t created or its path is incorrect when you imported it


  1. Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
  • Place a return statement to remove this error


  1. JSX expressions must have one parent element.ts(2657)
  • You have a closing tag placed in the wrong location (8355 63526 86 5683 227243)


  1. Found 2 elements with non-unique id
  • Just make sure your first input type tag has a different id(prop) value than the second input type tag


  1. Identifier ‘App’ has already been declared
  • Your functional/Root Component is already called App and you are importing another functional component

  • To fix this just give your import a different name and this will make the problem disappear


  1. The < blabla> is unrecognized
  • Usually function names and file names in JS are lowercased

  • But in React this is a NONO! If you want to render a react component names of Functional Comp must start with Lowercase

  • To Fix this if you want to keep your functional component lowercased change your imported file name to Upppercase

  • It is better to have your component and File Names as uppercase

  1. import './App.css'
  2. //Change the below statement to the following one
  3. //import message from './components/message'
  4. import Message from './components/message';
  5. function App(){
  6. return(
  7. <div className="App">
  8. <Message ></Message>
  9. </div>
  10. )
  11. }
  12. export default App;


  1. Importing Named Exports As Default Exports: Generates the error: ‘./components/MyNamedExport’ is imported as ‘MyNamedExport’
  1. export const MyNamedExport = () => {
  2. return(
  3. <div>
  4. Named Export
  5. </div>
  6. )
  7. }

Root Component: App.js … To Solve this wrap my MyNamedExport in Curly Braces

  1. //import MyNamedExport from './components/MyNamedExport';
  2. import { MyNamedExport } from './components/MyNamedExport';
  3. function App(){
  4. return(
  5. <div className="App">
  6. <MyNamedExport ></MyNamedExport>
  7. </div>
  8. )
  9. }
  10. export default App;


  1. Unknown DOM property for. Did you mean htmlFor
  • Change the for prop in your form tag to an htmlFor prop and this error will go away


  1. Too Many Rerenders
  • I goto my Setter Function of UseState Hook Take My file Count.js
  1. import { useState } from 'react';
  2. export const MyNamedExport = () => {
  3. const [count, setTheCount] = useState(0);
  4. return(
  5. <div>
  6. <button onClick={setTheCount(count+1)}>Count - {count} </button>
  7. </div>
  8. )
  9. }


  1. A Component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
  • This is due to not passing anything to the UseState Hook. When you pass undefined or null to a value within a React component along with an onChange that means this is an uncontrolled component


  • You are essentially going from uncontrolled to controlled input and this is a big NONO


  • To Fix this just pass in an empty string to the useState hook


  1. React Hook useEffect has a missing dependency: ‘userOne’. Either include it or remove the dependency array react-hooks/exhaustive-deps
  • This is saying we are using a variable in my useEffect hook but I am not including it in my dependency array

  • To fix this just include the variable in the dependency array

  • I goto the Root component to include it and it generates the error Too Many Rerenders
  1. import './App.css';
  2. import { MyNamedExport } from './components/MyNamedExport';
  3. function App(){
  4. return(
  5. <div className="App">
  6. <MyNamedExport ></MyNamedExport>
  7. </div>
  8. )
  9. }
  10. export default App;
  • Instead of passing the function by value I pass an arrow function to the event handler
  1. import { useState } from 'react';
  2. export const MyNamedExport = () => {
  3. const [count, setTheCount] = useState(0);
  4. return(
  5. <div>
  6. <button onClick={()=>setTheCount(count+1)}>Count - {count} </button>
  7. </div>
  8. )
  9. }
  1. Attempted import error: ‘x’ is not exported from ‘./components/x’.

If your remove the curly brace of your in your import statement this error goes away

  1. Class constructor X cannot be invoked without ‘new’

Make sure you tell react that you are trying to create a component by extending React.component


Instead of doing this:

  1. class Book extends React.Component


Change it to a default class component

  1. export default class Book extends Component

JSX

  • React’s Syntax for writing stuff a mix of XML and VanillaJS

How to resize images in React

  • Pass in an id prop to your img tag in your js file

  • Head over to your styles.css file and place a # in front of the value of the id you supplied without the quotes

How To accept the default package.json

  1. npm init -y

How Do You Pass Data from One Class Based Component To Another Class-Based Component? You use Props!

  1. import React, { Component } from 'react';
  2. import logo from './logo.svg';
  3. import "App.css"
  4. //Functional Component
  5. const Body = () => {
  6. <p className="App-Intro">
  7. Welcome Here
  8. </p>
  9. }
  10. //Header Component aka class Based Component
  11. class Header extends Component{
  12. render(){
  13. return(
  14. <header className="App-header">
  15. <img src="{logo}" className="App-logo" alt="logo" />
  16. <h1 className="App-title"> Welcome Here </h1>
  17. </header>
  18. );
  19. }
  20. }
  21. //Root Component and I pass the Header Component as props
  22. class App extends Component{
  23. render(){
  24. return(
  25. <div className="App">
  26. <Header ></Header>
  27. <Body ></Body>
  28. </div>
  29. );
  30. }
  31. }

Default Port Which React Runs On:

  • 3000

Webpack

  • module that bundles our JS code for it to be understood by multiple browsers

  • AKA it is resource loader

  • Any foreign module dependency is published for it to be understood by the browser

Webpack Bundler

  • npm module that bundles our JS code. It is in charge of collecting the app’s dependencies and merging them

  • … for it to be consumed by the web browser

Truthy or False Vals

  1. //checking for truthy or falsy values
  2. //toBeNull matches only to null
  3. //toBeUndefined matches only to Undefined
  4. //toBeDefined is the opposite of toBeUndefined
  5. //toBeTruthy matches anything that an if statement treats as true
  6. //toBeFalsy matches anything that an if statement treats as false

ReactJS Fundamentals You Must Know:

  1. Create React App Command

  2. JSX Syntax

  3. Components

  • Functional

  • Class Based Components

  1. The Difference between Props And State

  2. Conditional Rendering

  3. Component Lifecycle

  4. Lists And Keys

  5. The Difference Between Composition And Inheritance

  6. The Basic Hooks

  • useState

  • useEffect


ReactJS Advanced Topics

  1. Hooks

a. Custom Hooks

b. Common Hooks:

  • [ ] useCallback

  • [x] useRef

  • [x] useMemo

  • [ ] useReducer

  • [x] useContext

  1. Context

  2. Refs

  3. Render Props

  4. Code Splitting

  5. Higher Order Components

  6. Portals

  7. Error Boundaries

  8. Fiber Architecture

Next Step: Keep Learning………..

CodeSnippets

  1. rfc: React Functional Component

  2. race: React Arrow Function Component Export

  3. rafce: React Arrow Functional Component Export

  4. rcc: class component skeleton

  5. rfcp: React Functional Component With Prop Types

  6. rrc: class component skeleton with react-redux connect

  7. rrdc: class component skeleton with react-redux connect and dispatch

  8. rccp: class component skeleton with prop types after the class

  9. rcjc: class component skeleton without import and default export lines

  10. rcfc: class component skeleton that contains all the lifecycle methods

  11. rwwd: class component without import statements

  12. cwm: component will mount method skeleton

  13. cdm: componentDidMount method skeleton

  14. cwr: componentWillReceiveProps method

  15. scu: shouldComponentUpdate method

  16. cwup: componentWillUpdate method

  17. cdup: componentDidUpdate method

  18. cwun: componentWillUnmount method

  19. ren: render method

  20. sst: this.setState with object as parameter

  21. ssf: this.setState with function as parameter

  22. props: this.props

  23. state: this.state

  24. bnd: binds the this of method inside the constructor

  25. disp: MapDispatchToProps redux function

  26. html5: Blank html5 document

Other Ports To Run React On:

  • Range Of Ports: [0,65535] …. I am using Interval Notation FYI


How To Install Components Features Through NPM

  1. npm install -g create-react-component

Files Which Are Usually Deleted

  • App.css

  • App.test.js

  • logo.svg

  • setupTests.js

What is the difference between State And Props in React? When To Use State? When To Use Props

  • State houses the object vals which belong to a component

  • Props are we pass in between components… Typically between parent comp and child comp

  • Properties in a react component are vars that we pass to it by its parent component

  • State on the other hand is an immutable variable that is directly managed by the component

  • We can initialize state thanks to properties(props) and vice versa

  • When I want to display something in my component I use props

  • When I want to update something in my component or track something in my component I use state

  • When I want to print something use functional component with props

  • When Updating something I use state(more precisely the built in hook react provides me with useState)


How To Pass Data From One Part Of Your App to annother

  • The end goal of passing data is for it to reach the tree of the child component. Now to move data from the child to the parent component I use props.

What Is State? You will always here this keyword when dealing with ReactJS

  • State is just an object. State is used in the class component, and we must remember that state stores the component data and determines the component behavior


Memoization

  • The process by which we store a super heavy functional component in memory

  • I reuse this component thanks to Caching

Virtual DOM vs Real DOM

  • Virtual DOM has the exact same properties as Real DOM but virtual DOM doesn’t have the power to change things directly

  • DOM Manipulation is slow

  • Virtual DOM Manipulation is fast

IF YOU DO NOT KNOW WHAT THE DOM IS:

  • process by which we take all the nasty html elements and put them in a object that has tree structure

  • IOW it takes all the nasty HTML elements and gives it a nice structure

  • e.g.:

  • < document > is the parent:

  • < html > is the child of < document >

  • < head > and < body > are the children of < html >

  • < title > is the child of < head >

  • < h1-h6 > and < a > are the children of < body >

  • HTML DOM is a standard way of GETTING, CHANGING, ADDING, REMOVING html elements

How To Create A Component

  1. create-react-component nameofyourcomponent

Smart Components Vs Dumb Components

  • Smart Components are components which are at the application level that have the ability to execute functions and manage data

  • Dumb Components are components that strictly deal with the User Interface

How To Create A Column in file Whatever.js

  1. import React { Component } from 'react';
  2. export default Whatever extends Component {
  3. render() {
  4. return (
  5. <div className="col-md-4"></div>
  6. )
  7. }
  8. }

How To Create A Row in file Whatever.js

  1. import React { Component } from 'react';
  2. export default Whatever extends Component {
  3. render() {
  4. return (
  5. <div className="row"></div>
  6. )
  7. }
  8. }

How To Get the FE communicate with the BE: FOLLOW THESE STEPS EXACTLY

  1. Configure the BE first[NodeJS]—- have Nodemon and NodeJS installed
  1. Create a folder inside your project and call it backend

  2. within the folder run npm init to create a package.json

  3. Install express, cors, body-parser, morgan

  4. Create an index.js file and throw this stuff in it

  5. I create a db to have data in it so that my FE can consume it call it db.js

  1. let games = [
  2. { _id: 1, name: "San Andreas", runs: "PC" },
  3. { _id: 2, name: "Valorant", runs: "PC" },
  4. { _id: 3, name: "GTA 5", runs: "PC" }
  5. ];
  6. module.exports = games;

Creating Routes


  1. I want a route for games so I define routing for it I create it inside a folder called routes
  1. //the games.js file
  2. const express = require("express");
  3. const app = express();
  4. const cors = require("cors");
  5. const bodyParser = require("body-parser");
  6. const logger = require("morgan");
  7. const myGameRouter = require("./routes/games");
  8. const port = process.env.PORT || 3001;
  9. app.use(logger('dev'));
  10. app.use(cors());
  11. app.use(bodyParser.urlencoded({ extended: true }));
  12. app.use(bodyParser.json());
  13. app.use("/games", myGameRouter);
  14. //I listen to the port I defined
  15. app.listen(port, function() {
  16. console.log("Runnning on Port: " + port);
  17. });
  18. //creating a route to get the list of games
  19. router.get("/list", async (req, res) => {
  20. try {
  21. res.status(200).json({
  22. data: games
  23. });
  24. } catch (err) {
  25. res.status(400).json({
  26. message: "Some error occured",err
  27. });
  28. }
  29. });
  30. //creating a route to get a single game
  31. router.get("/list/:id", async (req, res) => {
  32. let { id } = req.params;
  33. id = Number(id);
  34. try {
  35. let game = games.find(game => game._id === id);
  36. res.status(200).json({
  37. data: game
  38. });
  39. } catch (err) {
  40. res.status(400).json({
  41. message: "Some error occured",
  42. err
  43. });
  44. }
  45. });
  46. module.exports = router;


Backend


  1. I goto my index.js file
  1. const express = require("express");
  2. const app = express();
  3. const cors = require("cors");
  4. const bodyParser = require("body-parser");
  5. const logger = require("morgan");
  6. const port = process.env.PORT || 3001;
  7. const myGameRouter = require("./routes/games");
  8. app.use(logger('dev'));
  9. app.use(cors());
  10. app.use(bodyParser.urlencoded({ extended: true }));
  11. app.use(bodyParser.json());
  12. app.use("/games", myGameRouter);
  13. //I listen to the port I defined
  14. app.listen(port, function() {
  15. console.log("Runnning on Port: " + port);
  16. });
  17. module.exports = app;


  1. I run my backend
  1. nodemon index.js

Frontend

  1. I create A react application
  1. npx create-react-app react-fe
  1. Add Bootstrap to the index.html file in the react-fe folder


  1. goto your root component and make App.js a class based component and export it


  1. have some state in your constructor
  1. import React, { Component } from "react";
  2. export default class App extends Component {
  3. constructor(someprops) {
  4. super();
  5. this.state = {
  6. list: true, //list of games will show if true
  7. card: false, //single game will be displayed if true
  8. games: [], //has the list of games stored in the be here
  9. game: {} //has 1 single game stored in the be here
  10. };
  11. }
  12. /*
  13. I need to get the list of games from the API
  14. using the lifecycle hook componentDidMount to have list of
  15. games stored inside the state before I mount the component
  16. */
  17. componentDidMount() {
  18. fetch("http://localhost:3001/games/list")
  19. .then(response => response.json())
  20. .then( responseJson=> {
  21. this.setState({ games:responseJson.data });
  22. },
  23. )}
  24. // Be able to view a single game
  25. showGame= id => {
  26. fetch(`http://localhost:3001/games/${id}`)
  27. .then(response => response.json())
  28. .then(
  29. responseJson=> {this.setState({ game:responseJson.data })},
  30. );
  31. this.setState({
  32. list:false,
  33. game:true
  34. });
  35. };
  36. render(){
  37. return(
  38. <div className ="container">
  39. {this.state.list ? (
  40. <div className="list-group">
  41. {this.state.games.map(game => (
  42. <li onClick={() => this.showGame(game._id)}
  43. className="list-group-item list-group-item-action"
  44. >
  45. {game.name}
  46. </li>
  47. ))}
  48. </div>
  49. ) : null}
  50. </div>
  51. {this.state.card ? (
  52. <div class="card" style={{ width: "18rem" }}>
  53. <div class="card-body">
  54. <h5 class="card-title">{this.state.player.name}</h5>
  55. <p class="card-text">{this.state.player.runs}</p>
  56. <div onClick={() => this.showGame()} class="btn btn-primary">Back</div>
  57. </div>
  58. </div>
  59. ) : null}
  60. )
  61. }
  1. I run my frontend
  1. npm start

Prevents the form from submiting

  1. ev.preventDefault()
  2. //when you submit an application the whole page refreshes in the case of forms

How to Render Sth In React


I can put 27375 in place of this.state.pascal and it will render

  1. import React, { Component } from "react";
  2. class Pasc extends Component{
  3. state = {
  4. pascal: 1
  5. };
  6. render(){
  7. return(
  8. <div>{this.state.pascal}</div>
  9. );
  10. }
  11. }
  12. export default Pasc;

Destructuring Explained in React


Without Destructuring

  1. //Without destructuring I would have the following
  2. var example = useState('yourStateGoesHereAndAskNelanToLearnLLP');
  3. var firstElement = example [0];
  4. var secondElement = example[1];


Using Destructuring

  1. const [firstElement, secondElement] = useState('yourStateGoesHereAndAskNelanToLearnLLP');


Example 2

  1. //Without destructuring
  2. const hookForNumbers = useState(2);
  3. const number = hookForNumbers[0];
  4. const setNumber = hookForNumbers[1];
  5. //with destructuring
  6. const [number, setNumber] = useState(2);


Some Good Practices

  • Fetch Your Data not in the render function but in the lifecycle method componentDidMount Why?

  • componentDidMount will run only if your component has been mounted to the dom AT LEAST ONCE

  • To know if you have fetched the data or completed the data we use state


8. Data Fetching From An API Misconception

  • Wrong: Fetch the Data from An API then you render it to the DOM and no render if you haven’t fetched the data

  • True: Fetch the data from A Resource(aka API). When the data comes in, you update the state thanks to the hook and we render the new state to the dom


How To Fetch Data Using the Fetch Function From An API using the desired HTTP Method

  1. fetch('https://localhost:3000/pages', {
  2. method: 'POST',
  3. headers: {"Content-type": "application/json"},
  4. body: JSON.stringify({ title, codes, category })
  5. })



Some Useful Npm Packages to Use In React:

UI Component Libraries

  • @material-ui/core: React MaterialUI components

  • react-bootstrap: Bootstrap4 components built with React

  • semantic-ui-react: React Component Library

  • reactstrap: Stateless React Components for Bootstrap4

Individual UI Component Libraries

  • react-spinners: loading spinners for your react app

  • react-loader-spinner: spinner component which can be used in your async.await operation

  • react-dropdown: Simple Dropdown component

  • react-slick: Carousel component built with React

  • react-responsive-carousel: A responsive carousel component

  • react-images: A responsive, mobile-friendly, highly-customizable carousel component for displaying media in React

  • react-tabs: An easy-tab component for your React App

CSS In JS

  • styled-components: super easy to use library which lets you style your components at ease

HTTP stuff

  • axios: Promised based http client for the browser and NodeJS

Routing:

  • react-router-dom: DOM Bindings in React Router

State Management:

  • redux: state container for your JS apps

  • react-redux: official React Binding for Redux

Context API

  • Context provides a way to pass data through multiple components tree without having to pass props down manually at every level starting from the parent component

  • Props drilling is the process by which we pass data from component A to Component B thanks to props and the more components we have the more complex it gets

  • Thanks to ContextAPI I have a central store where my data lives

  • We can treat ContextAPI similar to Redux which gives me a central store which houses my data

  • The store can be inserted into any component

  • ContextAPI provides a way to pass data through the component tree without having to pass props down manually at every level

  • The consumer is a component which is consuming the value

There are three levels of ContextAPI

  1. Level 1: Context

  2. Level 2: Provider —> Used in the parent component

  3. Level 3: Consumer

  1. /*
  2. createContext Function creates the context or we can see it creates a central data store for me to store my data
  3. */
  4. const ThemeContext = React.createContext('light');
  5. class App extends React.Component {
  6. render() {
  7. // Use a Provider to pass the current theme to the tree below.
  8. //A provider is a component which is used to provide the value to all my components
  9. // Any component can read it, no matter how deep it is.
  10. // In this example, we're passing "dark" as the current value.
  11. //I wwrap the parent component in between my provider
  12. return (
  13. <ThemeContext.Provider value="dark">
  14. <Toolbar ></Toolbar>
  15. </ThemeContext.Provider>
  16. );
  17. }
  18. }
  19. // A component in the middle doesn't have to
  20. // pass the theme down explicitly anymore.
  21. function Toolbar() {
  22. return (
  23. <div>
  24. <ThemedButton ></ThemedButton>
  25. </div>
  26. );
  27. }
  28. class ThemedButton extends React.Component {
  29. // Assign a contextType to read the current theme context.
  30. // React will find the closest theme Provider above and use its value.
  31. //This is a consumer FYI
  32. // In this example, the current theme is "dark".
  33. static contextType = ThemeContext;
  34. render() {
  35. return <Button theme={this.context} ></Button>;
  36. }
  37. }

ContextAPI Stuff

I goto my index.js

  1. import React from "react";
  2. import ReactDOM from "react-dom";
  3. import "bootstrap/dist/css/bootstrap.min.css";
  4. import {BrowserRouter} from "react-router-dom";
  5. import Theme from "./Context/Theme";
  6. ReactDOM.render(
  7. <BrowserRouter>
  8. <Theme></Theme>
  9. </BrowserRouter>,
  10. document.getElementById("root")
  11. );

I goto my Theme.js file which will have a parent component(Theme class) and a Child Component(CurrentTheme )

  1. import React, { Component } from "react";
  2. //creating the context and specifying a default value
  3. const ThemeContext = React.createContext("light");
  4. /*
  5. line 643 is where I make a call to the provider and I place my parent component there
  6. I can change the theme from light to dark by passing a value prop to my prop and supply it with an argument of dark
  7. Instead of passing props from one compoent to another in the form of layer in context api I do not have to pass props to any component actually
  8. Just wwrap your component within a provider
  9. */
  10. //parent component
  11. export default class Theme extends Component{
  12. render(){
  13. return(
  14. <div>
  15. <ThemeContext.Provider value="Dark">
  16. <CurrentTheme ></CurrentTheme>
  17. </ThemeContext.Provider>
  18. </div>
  19. );
  20. }
  21. }
  22. //child component 1
  23. function CurrentTheme(){
  24. return(
  25. <div>
  26. <SecondChild ></SecondChild>
  27. </div>
  28. )
  29. }
  30. class SecondChild extends Component{
  31. //way #2 to initialize context
  32. static contextType = ThemeContext()
  33. render(){
  34. return(
  35. <div>
  36. <h1>Using Context API</h1>
  37. </div>
  38. )
  39. }
  40. }
  41. /*initializing context property outside of class
  42. Way#1 to initialize context
  43. SecondChild.contextType = ThemeContext
  44. */

1 How to install prereqs for react and all other dependencies necessary to your project

  1. mkdir my-react-app
  2. cd my-react-app
  3. npm init --y
  4. npm install react react-dom
  5. npm install --save-dev webpack webpack-dev-server html-webpack-plugin @babel/core babel-loader @babel/preset-env @babel/preset-react

2: Create React Application using the create-react-app command

  1. npx create-react-app

3: Remove the following 5 files that come shipped with the create-react-app command

  • App.test.js

  • index.css

  • logo.svg

  • serviceWorker.js

  • setupTests.js

4. React Project Layout. If you are build a SPA no need for components dir ignore this step and any subsequent one

  1. ├── README.md
  2. ├── node_modules
  3. ├── package.json
  4. ├── .gitignore ------- list the files you do not want git to track here
  5. ├── public
  6. ├── favicon.ico
  7. ├── index.html ------ to bootstrap your react app import it here
  8. └── manifest.json
  9. └── src
  10. ├── App.css ---------------- styling
  11. ├── App.js ----------------- root component
  12. ├── App.test.js ------------ unit tests
  13. ├── components
  14. ├── Home.jsx
  15. ├── NameOfYourSecondPage.jsx
  16. ├── NameOfYourThirdPage.jsx
  17. ├── NameOfYourFourthPage.jsx
  18. ├── NameOfYourNthPage.jsx
  19. ├── Navigation.jsx
  20. ├── Footer.jsx
  21. ├── index.css
  22. ├── index.js
  23. ├── logo.svg
  24. └── serviceWorker.js

For Projects

5. Create a components folder in your src folder

  1. ├── README.md
  2. ├── node_modules
  3. ├── package.json
  4. ├── .gitignore
  5. ├── public
  6. ├── favicon.ico
  7. ├── index.html
  8. └── manifest.json
  9. └── src
  10. ├── App.css
  11. ├── App.js
  12. ├── App.test.js
  13. └── components
  14. └── Footer
  15. └── Navbar
  16. ├──index.js
  17. ├──
  18. └── images
  19. └── pages
  20. └── videos
  21. ├── index.css
  22. ├── index.js
  23. ├── logo.svg
  24. └── serviceWorker.js

5. React Typescript Project Layout

  1. .
  2. ├── .gitignore
  3. ├── .editorconfig
  4. ├── .env
  5. ├── README.MD
  6. ├── package.json
  7. ├── package-lock.json
  8. ├── tsconfig.json
  9. ├── tslinst.json
  10. ├── public/
  11. ├── index.html
  12. └── loader.css
  13. ├── srcipts/
  14. └── mjml-compile.js
  15. └── src/
  16. ├── assets/
  17. └── logo.svg
  18. ├── components/
  19. └── button/
  20. ├── index.tsx
  21. └── button.specs.ts
  22. ├── middlewares/
  23. └── auth.tsx
  24. ├── pages/
  25. ├── root.tsx
  26. ├── home.tsx
  27. └── login.tsx
  28. ├── routes/
  29. └── index.tsx
  30. ├── services/
  31. └── http.ts
  32. ├── styles/
  33. ├── ant-override.scss
  34. ├── _variables.scss
  35. └── index.scss
  36. ├── utils/
  37. └── index.ts
  38. ├── app.tsx
  39. └── index.tsx

6. If you are a build a MPA run this command to setup routing

  1. npm i react-router-dom

7. Schema hasn’t been registered for model

  • Check your arguments for mongoose.model call

8. Unable to enter data in a form?

  • Make sure you take a look at the value prop you passed to the form element

  • Passing a value prop X means the value will always be X

  • Removing the value prop altogether transforms your input field from controlled to uncontrolled