What is React?

React Render HTM

3-Upgrade React

6-React Class Components

7-React Props

8-React Events

9-React Conditional Rendering

10-React Lists

11-React Forms

12-React Router

13-React Memo

14-Styling React Using CSS

15-Styling React Using Sass

16-React Hooks

16.1-React useState Hook

16.2-React useEffect Hooks

16.3-React useContext Hook

16.4-React useRef Hook

16.5-React useReducer Hook

16.6-React useCallback Hook

16.7-React useMemo Hook

16.8-React Custom Hooks

What is React?

React, sometimes referred to as a frontend JavaScript framework, is a JavaScript library created by Facebook.



How does React Work?

React creates a VIRTUAL DOM in memory .React creates a VIRTUAL DOM in memory.


React Getting Started


React Directly in HTML

HTML Example

<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script>
<head>



Setting up a React Environment

  1. If you have npx and Node.js installed
  2. you can create a React application by using create-react-app
  3. Run this command to create a React application named my-react-app: npx create-react-app my-react-app
  4. Run the React Application: cd my-react-app

React Render HTM

  1. by using a function called createRoot()
  2. its method render()

The createRoot Function

  1. The createRoot() function takes one argument an HTML element

The render Method

  1. called to >define the React component that should be rendered
  2. render where? index.html in the folder public in the <div>

The render Method

Display a paragraph inside an element with the id of "root":

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

Hello

);

The result is displayed in the <div id="root"> element:

<body>
<div id="root"></div>
</body>
import React from 'react';
import ReactDOM from 'react-dom/client';


const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<p>Hello</p>);


The HTML Code

===============

Example

Create a variable that contains HTML code and display it in the "root" node:

const myelement = (
<table>
<tr>
<th>Name</th>
</tr>
<tr>
<th>Ayman</th>
</tr>
<tr>
<th>Ahmed</th>
</tr>
</table>
);

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(myelement);




3-Upgrade React

Upgrading an existing React application to version 18 only requires two steps.

Step 1: Install React 18

To install the latest version, from your project folder run the following from the terminal:

npm i react@latest react-dom@latest

Step 2: Use the new root API

In order to take advantage of React 18's concurrent features you'll need to use the new root API for client rendering.

// Before
import ReactDOM from 'react-dom';
ReactDOM.render(<App />, document.getElementById('root'));
// After
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);




3.1-What is ES6? (CAVA DSMT)

  1. ES6 stands for ECMAScript 6.

3.2-What are the new features in ES6?

  1. Classes
  2. Arrow Functions
  3. Variables (let, const, var)
  4. Destructuring
  5. Modules
  6. Ternary Operator
  7. Spread Operator




3.1-React ES6 Classes

  1. A class is a type of function
  2. but instead of using the keyword function
  3. we use the keyword class
  4. the properties are assigned inside a constructor() method.

Classes Example

class Car {
constructor(name) {
this.brand = name;
}
}

Create an object called "mycar" based on the Car class:

<!DOCTYPE html>
<html>

<body>

<script>
class Car {
constructor(name)
this.brand = name;
} } const mycar = new Car("Ford");

document.write(mycar.brand);
</script>

</body>
</html>

Create a method named "present":

<html>

<body>

class Car {
constructor(name) {
this.brand = name;
}
}

present() {
return 'I have a ' + this.brand;
}
}
const mycar = new Car("Ford");
mycar.present();
</script>

</body>
</html>




3.2-React ES6 Arrow Functions

  1. Arrow functions allow us to write shorter function syntax:

Arrow Function

<!DOCTYPE html>
<html>

<body>

<p id="demo"></p>

<script><br>
hello = () => {
return "Hello world!"
}

document.getElementById("demo").innerHTML = hello();
</script>

</body>
</html>




3.3-React ES6 Variables

3.4-React ES6 Array Methods

  1. There are many JavaScript array methods.
  2. One of the most useful in React is the .map() array method.
  3. The .map() method allows you to run a function
  4. returning a new array as the result
  5. In React,map() can be used to generate lists




Generate a list of items from an array:

import React from 'react';
import ReactDOM from 'react-dom/client';
const myArray = ['apple', 'banana', 'orange'];

const myList = myArray.map((item) => <p>{item}</p>)

const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(myList);




3.5-React ES6 Destructuring

  1. We may have an array object that we are working with, but we only need some of the items contained in these.

assigning array items to a variable With destructuring:

const vehicles = ['mustang', 'f-150', 'expedition'];

const [car, truck, suv] = vehicles;

If we only want the car and suv we can simply leave out the truck but keep the comma

const vehicles = ['mustang', 'f-150', 'expedition'];

const [car,, suv] = vehicles;

Destructuring comes in handy when a function returns an array:

<script>
function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;

return [add, subtract, multiply,divide];
}

const [add, subtract, multiply , divide]= calculate(4,7);
document.write("<p>Sum: " + add + "</p>");
document.write("<p>Difference " + subtract + "</p>");
document.write("<p>Product: " + multiply + "</p>");
document.write("<p>Quotient " + divide + "</p>");

</script>

</body>
</html>

Destructring Objects : here is the old way of using a function before

const vehicleOne = { brand: 'Ford', model: 'Mustang', type: 'car', year :2024, color: 'red' } myVehicle(vehicleOne); //old way function myVehicle(vehicleOne) { const message = 'My' + vehicle.type + 'is a ' + vehicle.color + ' '+ vehicle.color + ' ' + vehicle.brand + ' '+ vehicle.model + ' ' ; }

Here is the new way of using an object insde a function with destructing :

<!DOCTYPE html>
<html>

<body>
<script>
<p id="demo"></p>

const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}

myVehicle(vehicleone);

function myVehicle ({type, color , brand , model}) {
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
}

document.getElementById("demo").innerHTML = message;
}
</script>

</body>
</html>




3.6-React ES6 Spread Operator





3.7-React ES6 Modules

  1. JavaScript modules allow you to break up your code into separate files.
  2. ES Modules rely on the import and export statements.
  3. You can export a function or variable from any file.
  4. There are two types of exports:Named and Default.Default(ND).
  5. Let us create a file named person.js

A-Named Exports

You can create named exports two ways:

  1. In-line individually,
  2. all at once at the bottom.

In-line individually,

export const name = "Jesse"
export const age = 40

All at once at the bottom:

const name = "Jesse"
const age = 40

export { name, age }

B-Default Exports

  1. Let us create another file, named message.js
  2. use the file for demonstrating default export.
  3. You can only have one default export in a file.

Default Exports Example file name: message.js

const message = () => {
const name = "Jesse"
const age = 40;
return name + ' is ' + age + 'years old';
};

export default message;


Import

  1. You can import modules into a file in two ways
  2. based on if they are named exports or default exports.
  3. Named exports must be destructured using curly braces.
  4. Default exports do not.

Import named exports from the file person.js:

<!DOCTYPE html>
<html>

<body>

<p id="demo"></p>

<script type="module">
import {name, age } from "./person.js;"

document.getElementById("demo").innerHTML = "My name is " + name;
document.getElementById("demo").innerHTML += ", I am " + age + ".";

</script>

</body>
</html>

Import a default export from the file message.js:

<!DOCTYPE html>
<html>

<body>

<p id="demo"></p>

<script type="module">
import message from "./message.js";

document.getElementById("demo").innerHTML = message();

</script>

</body>
</html>




3.8-React ES6 Ternary Operator





4-React Render HTML





5-React Components

  1. Components are like functions thatreturn HTML elements.
  2. Components are independent
  3. Components are reusable bits of code.
  4. Components come in two types , Class components and Function components(CF)
  5. When creating a React component, the component's name MUST start with an upper case letter.

A-Class Component

Create a Class component called Car

class Car extends React.component {
render() {
return

Hello, this is my Car

;
}
}

B-Function Component

  1. Function components can be written using much less code, are easier than the class components

Create a Function component called Car

function Car(){
return

Hi, I am a React


}

Rendering a Component

  1. Now your React application has a component called Car,
  2. this component returns an <h2> element.
  3. To use this component in your application use similar syntax as normal HTML: <Car />

Display the Car component in the "root" element:

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

function Car() {
return <h2> hi , i am a React Developer!</h2>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<car/>);

Props

  1. Components can be passed as props
  2. props stands for properties
  3. Props are like function arguments
  4. you send the props (arguments) into the component as attributes.

Use an attribute to pass a color to the Car component

use it in the render()function :

import React form 'react';
import ReactDOM from 'react-dom/client';

function Car (props) {
return <h2<I am a {props.color} Car!</h2<;

} const root = ReactDOM.creatRoot(document.getElementById('root'));
root.render(<car color="red"/>);




6-React Class Components

  1. Before React 16.8, Class components were the only way to track state and lifecycle on a React component.
  2. Function components were considered "state-less".
  3. With the addition of Hooks,Function components are now almost equivalent to Class components.
  4. you will probably never need to use a Class component in React.
  5. skip this section, and use Function Components instead.




7-React Props

  1. Props are arguments passed into React components .
  2. Props are passed to components via HTML attributes.
  3. props stands for properties.
  4. React Props are like function arguments in JavaScript and attributes in HTML.
  5. To send props into a component, use the same syntax as HTML attributes:
  6. Add a "brand" attribute to the Car element:

    const myElement = ;
  7. The component receives the argument as a props object:
  8. Use the brand attribute in the component:

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

    function Car(props) {
    return <h2>I am a { props.brand }!</h2>;

    } const myElement = ;

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(myElement);
  9. how you pass data from one component to another, as parameters.
  10. Send the "brand" property from the Garage component to the Car component:

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

    function Car(props) {
    return <h2>I am a { props.brand }!</h2>;
    }

    function Garage() {
    return (
    <>
    <h1>Who lives in my garage?</h1>
    <Car brand="Ford" />
    </>
    );
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Garage />);




8-React Events

    React event syntax

    <button onClick={shoot}>Take the Shot!</button>
  1. like HTML DOM events,React can perform actions based on user events.
  2. React has the same events as HTML: click, change, mouseover etc.
  3. React events are written in camelCase syntax
  4. for example: onClick
  5. React event handlers are written inside curly braces:onClick={shoot}
  6. React event syntax

    <button onClick={shoot}>Take the Shot!</button>

    put the shoot function inside the Football component:

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

    function Football() {
    const shoot = () => {
    alert("Great Shot!");
    }

    return (
    <button onClick={shoot}>Take the shot!</button>
    );
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Football />);




9-React Conditional Rendering

  1. In React, you can conditionally render components
  2. We can use the if JavaScript operator to decide which component to render.
  3. We'll use these two components:

    function MissedGoal() {
    return <h1>MISSED!</h1>;
    }

    function MadeGoal() {
    return <h1>Goal!</h1>;
    }

    Now, we'll create another componentthat chooses which component to render based on a condition:

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

    function MissedGoal() {
    return <h1>MISSED!</h1>;
    }

    function MadeGoal() {
    return <h1>GOAL!</h1>;
    }

    function Goal(props) {
    const isGoal = props.isGoal;
    if (isGoal) {
    return <MadeGoal/>;
    }
    return <MissedGoal/>;
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Goal isGoal={false} />);

10-React Lists

  1. In React, you will render lists with some type of loop.
  2. The JavaScript map() array method is generally the preferred method.
  3. Let's render all of the cars from our garage:

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

    function Car(props) {
    return <li>I am a { props.brand }</li>;
    }

    function Garage() {
    const cars = ['Ford', 'BMW', 'Audi'];
    return (
    <>v <h1>Who lives in my garage?</h>
    <ul>
    {cars.map((car) => <Car brand={car} />)}
    </ul>
    </>
    );
    }
    const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Garage />); /* If you run this example in your create-react-app, you will receive a warning that there is no "key" provided for the list items. */
  4. When you run this code in your create-react-app,
  5. it will work but you will receive a warning that there is no "key" provided for the list items.
  6. Keys allow React to keep track of elements
  7. This way, if an item is updated or removed, only that item will be re-rendered instead of the entire list.
  8. Keys need to be unique to each sibling.
  9. But they can be duplicated globally.
  10. the key should be a unique ID assigned to each item
  11. import React from 'react';
    import ReactDOM from 'react-dom/client';

    function Car(props) {
    return
  12. I am a { props.brand }
  13. ;
    }

    function Garage() {
    const cars = [
    {id: 1, brand: 'Ford'},
    {id: 2, brand: 'BMW'},
    {id: 3, brand: 'Audi'}
    ];
    return (
    <>

    Who lives in my garage?



      {cars.map((car) => )}


    );
    }

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

11-React Forms

12-React Router

13-React Memo

14-Styling React Using CSS

15-Styling React Using Sass





16-React Hooks

  1. Hooks allow function components to have access to state and other React features
  2. Because of this, class components are generally no longer needed.
  3. Although Hooks generally replace class components,
  4. Hooks allow us to "hook" into React features such as state and lifecycle methods.
  5. import React, { useState } from "react"; import ReactDOM from "react-dom/client"; function FavoriteColor() { const [color, setColor] = useState("red"); return ( <> <h1>My favorite color is {color}!</h1> <button type="button" onClick={() => setColor("blue")} >Blue ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render();
  6. You must import Hooks from react.
  7. Here we are using the useState Hook to keep track of the application state.
  8. State generally refers to application data or properties that need to be tracked.
  9. There are 3 rules for hooks:
    1. Hooks can only be called inside React function components.
    2. Hooks can only be called at the top level of a component.
    3. Hooks cannot be conditional
  10. Hooks will not work in React class components .

16.1-React useState Hook

  1. The eact useState HookR allows us to track state in a function component.
  2. State generally refers to data or properties that need to be tracking in an application.
  3. To use the useState Hook we first need to import it into our component
  4. At the top of your component, import the useState Hook.

    import { useState } from "react";
  5. We initialize our state by calling useState in our function component.
  6. useState accepts an initial state and returns two values:
    1. The current state
    2. A function that updates the state
  7. Initialize state at the top of the function component.

    import { useState } from "react";

    function FavoriteColor() {
    const [color, setColor] = useState("");
    }
  8. we are destructuring the returned values from useState.
  9. The first value, color, is our current state
  10. The second value, setColor, is the function that is used toupdate our state.
  11. These names are variables that can be named anything you would like.
  12. we set the initial state to an empty string: useState("")

16.2-React useEffect Hooks

  1. The useEffect Hook allows you to perform side effects in your components.
  2. Some examples of side effects are: FDT
    1. Fetching data
    2. Directly updating the DOM
    3. Timers
  3. useEffect accepts two arguments.
  4. The second argument isoptional.
  5. useEffect(<function>, <dependency>)
  6. Let's use a timer as an example.
  7. Use setTimeout() to count 1 second after initial render:

    import { useState, useEffect } from "react";
    import ReactDOM from "react-dom/client";

    function Timer() {
    const [count, setCount] = useState(0);

    useEffect(() => {
    setTimeout(() => {
    setCount((count) => count + 1);
    }, 1000);
    });

    return <h1>I've rendered {count} times!</h1>;
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Timer />);
  8. But wait!! It keeps counting even though it should only count once!
  9. useEffect runs on every render.
  10. That means that when the count changes, a render happens,
  11. which then triggers another effect
  12. This is not what we want.
  13. There are several ways to control when side effects run.
  14. We should always include the second parameter which accepts an array.
  15. We can optionally pass dependencies to useEffect in this array.
  16. 1. No dependency passed:

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

    2. An empty array:

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

    3. Props or state values:

    useEffect(() => {
    //Runs on the first render
    //And any time any dependency value changes
    }, [prop, state]);
    So, to fix this issue, let's only run this effect on the initial render.

    Only run the effect on the initial render:

    import { useState, useEffect } from "react";
    import ReactDOM from "react-dom/client";

    function Timer() {
    const [count, setCount] = useState(0);

    useEffect(() => {
    setTimeout(() => {
    setCount((count) => count + 1);
    }, 1000);
    }, []); // >- add empty brackets here

    return <h1>'ve rendered {count} times!</h1>;
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Timer />);

    Here is an example of a useEffect Hook that is dependent on a variable.

    If the count variable updates, the effect will run again:

    import { useState, useEffect } from "react";
    import ReactDOM from "react-dom/client";

    function Counter() {
    const [count, setCount] = useState(0);
    const [calculation, setCalculation] = useState(0);

    useEffect(() => {
    setCalculation(() => count * 2);
    }, [count]); // <- add the count variable here

    return ( <> <p>Count: {count}</p>
    <button onClick={() => setCount((c) => c + 1)}>+</button>
    <p>Calculation: {calculation}</p>
    </>
    );
    }

    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<Counter />);
    If there are multiple dependencies, they should be included in the useEffect dependency array.





16.3-React useContext Hook

  • React Context is a way to manage state globally.
  • It can be used together with the useState Hook
  • to share state between nested components more easily than with useState alone.


  • The Problem:
    1. State should be held by the highest parent component in the stack
    2. that requires access to the state.
    3. To illustrate, we have many nested components.
    4. The component at the top and bottom of the stack need access to the state.
    5. To do this without Context,
    6. we will need to pass the state as "props" through each nested component.
    7. This is called "prop drilling".

      Passing "props" through nested components:

      import { useState } from "react";
      import ReactDOM from "react-dom/client";

      function Component1() {
      const [user, setUser] = useState("Jesse Hall");

      return (
      <>
      <h1>h1>{`Hello ${user}!`}</h1>
      <Component2 user={user} />
      </>
      );
      }

      function Component2({ user }) {
      return (
      <>
      <h1>Component 2</h1>
      <Component3 user={user} />
      </>
      );
      }

      function Component3({ user }) {
      return (
      <>
      <h1>Component 3</h1>
      <Component4 user={user} />
      </>
      );
      }

      function Component4({ user }) {
      return (
      <>
      <h1>Component 4</h1>
      <Component5 user={user} />
      </>
      );
      }
      function Component5({ user }) {
      return (
      <>
      <h1>Component 5</h1> <h2>{`Hello ${user} again!`}</h2>
      </>
      );
      }

      const root = ReactDOM.createRoot(document.getElementById('root'));
      root.render(<Component1 />);
      1. Even though components 2-4 did not need the state
      2. they had to pass the state along so that it could reach component 5.
  • The Solution:
    1. The solution is to create context.
    2. To create context, you must Import createContext and initialize it:

      import { useState, createContext } from "react";
      import ReactDOM from "react-dom/client";

      const UserContext = createContext()
    3. Next we'll use the Context Provider to wrap the tree of components that need the state Context.
  • Context Provider:
    1. Wrap child components in the Context Provider



    16.4-React useRef Hook

    16.5-React useReducer Hook

    16.6-React useCallback Hook

    16.7-React useMemo Hook

    16.8-React Custom Hooks