[go: up one dir, main page]

0% found this document useful (0 votes)
34 views17 pages

React_-_The_Complete_Guide_2024 - Copy

The document is a comprehensive guide to React, a JavaScript library for building user interfaces, highlighting its advantages over vanilla JavaScript, such as simplified state management and component-based architecture. It discusses the setup required for React projects, including the use of tools like Vite and npm, and provides examples of dynamic elements and coding approaches in React. Additionally, it covers fundamental JavaScript concepts relevant to React development, including variables, functions, and array methods.

Uploaded by

dblue4396
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views17 pages

React_-_The_Complete_Guide_2024 - Copy

The document is a comprehensive guide to React, a JavaScript library for building user interfaces, highlighting its advantages over vanilla JavaScript, such as simplified state management and component-based architecture. It discusses the setup required for React projects, including the use of tools like Vite and npm, and provides examples of dynamic elements and coding approaches in React. Additionally, it covers fundamental JavaScript concepts relevant to React development, including variables, functions, and array methods.

Uploaded by

dblue4396
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

React - The Complete Guide

2024:
source : https://coursehunter.net/course/udemy-react16-complete-guide?
lesson=2

notes:
React ⇒ is a JavaScript library for building user interfaces.

why to use it ?
⇒ to insure smooth user experiences and it uses JS in the browser to update
the page and the user interface without reloading the webpage.

why not use JavaScript ?

writing complex JavaScript code quickly becomes cumbersome.

Complex JavaScript code quickly becomes error-prone.

its hard to maintain or edit.

React is offers a more simpler mental model.

React Vs Vanilla JavaScript:


Vanilla JavaScript React

A JavaScript library for building


Refers to plain JavaScript user interfaces, particularly
without any libraries or single-page applications. It
Purpose and frameworks. It's used to allows developers to build
Use: manipulate the DOM, handle encapsulated components that
events, and perform other manage their own state and
front-end tasks directly. compose them to create
complex UIs.

Components You manually manage HTML Encourages the use of


and Structure: elements, their state, and components, which are
their interactions. The code reusable, self-contained
can become complex and modules that describe parts of

React - The Complete Guide 2024: 1


Vanilla JavaScript React
hard to manage as the the UI. This modular approach
application grows. simplifies development and
maintenance.

Provides a built-in state


State is managed manually,
management system through
State often requiring complex logic
the useState and useReducer
Management: to keep the UI in sync with
hooks, which makes it easier to
the underlying data.
manage and update the state.

Utilizes a virtual DOM, which is


Directly manipulates the DOM
a lightweight copy of the actual
using methods like
DOM. React updates the virtual
DOM document.getElementById or
DOM and then efficiently
Manipulation: querySelector . This can lead
updates the actual DOM to
to performance issues and
match, leading to better
bugs if not handled carefully.
performance and simpler code.

Introduces JSX, a syntax


Uses HTML and JavaScript extension that allows writing
separately. HTML defines the HTML-like code within
JSX:
structure, and JavaScript JavaScript. This makes it easier
manipulates it. to visualize the UI and keep
markup and logic together.

Requires learning additional


concepts like JSX,
Requires a good
components, props, and state.
Learning understanding of core
However, it simplifies complex
Curve: JavaScript concepts and the
tasks and improves
DOM API.
productivity for large
applications.

Comes with a rich ecosystem,


including libraries like React
Relies on the broader Router for routing and Redux
Ecosystem and JavaScript ecosystem but for state management. It also
Tools: doesn’t have specific tools or has development tools like
conventions. Create React App for project
setup and React DevTools for
debugging.

React - The Complete Guide 2024: 2


In summary, React abstracts many of the complexities involved in building modern
web applications, providing a more structured and efficient way to develop UIs
compared to vanilla JavaScript.

When referring to "dynamic elements" in the context of web development, it


typically means elements of a webpage that can change, update, or interact with
the user without requiring a full page reload. Dynamic elements are crucial for
creating a responsive and interactive user experience.

examples on some dynamic elements:

1. Forms with Live Validation:

document.querySelector('input').addEventListener('input', function(ev
const value = event.target.value;
if (value.length < 5) {
event.target.style.borderColor = 'red';
} else {
event.target.style.borderColor = 'green';
}
});

//using react
function MyForm() {
const [inputValue, setInputValue] = useState('');

const handleChange = (event) => {


setInputValue(event.target.value);
};

return (
<input
type="text"
value={inputValue}
onChange={handleChange}

React - The Complete Guide 2024: 3


style={{ borderColor: inputValue.length < 5 ? 'red' : 'green' }}
/>
);
}

2. Dynamic Content Loading with Fetch:

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
const list = document.getElementById('data-list');
data.forEach(item => {
const listItem = document.createElement('li');
listItem.textContent = item.name;
list.appendChild(listItem);
});
});

//using React
function DataList() {
const [data, setData] = useState([]);

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data));
}, []);

return (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>

React - The Complete Guide 2024: 4


);
}

3. Interactive Elements with Event Listeners:

document.querySelector('#button').addEventListener('click', function(
document.querySelector('#content').textContent = 'Button was clicke
});

//using React
function InteractiveComponent() {
const [message, setMessage] = useState('');

const handleClick = () => {


setMessage('Button was clicked!');
};

return (
<div>
<button onClick={handleClick}>Click Me</button>
<p>{message}</p>
</div>
);
}

writing code approaches :

in React ⇒ you define the target UI state(s) - not the steps to get there,
instead, React will figure out & perform the necessary steps. (Declarative ).

in JavaScript ⇒ you Define the steps not the goal (Imperative).

React - The Complete Guide 2024: 5


//Declarative React (define the goal n // Imperative Vanilla JavaScript (defin
let content: let btn = document.querySelector("bu
if(user.isLoggedIn) { if(user.isLoggedIn){
content = <button>Continue</butto btn.textContent = "Continue";
}else{ }else{
content = <button>Log In</button> btn.textContent = "Log In";
} }
return content; document.body.append(btn);

To start a react project in the browser URL bar just write react.new and it should
open a sandbox code environment for writing code. and that gives you an in-
browser development environment.

to create a react project locally in you’re VScode you need to install node.js ,
npm and vite

then you need to write in the terminal npm create vite@latest folder-name .

to once and (initially after creating a new project,) install all the local packages
necessary for your project use npm install .

starts a development preview server that allows you to view the


npm run dev

web app you’re working on.

keep npm run dev up and running whilst working on your code, Quit it anytime
via CTRL + C , restart it once you start working again.

Why do we need a special project setup in order to


work with react ?
that’s because using html code inside a JavaScript file(.JSX) isn't supported
by the browser that's why we need to use vite and npm .

React code must be TRANSFORMED & OPTIMIZED

React - The Complete Guide 2024: 6


JS Refresher:
JavaScript can be executed in many environments:

1. in the Browser (i.e. as part of the websites): JavaScript code can be


included in any website. the code then executes inside the browser (i.e. on
the machine of the website of the visitor).

2. On any Computer (e.g. Server-side code): Thanks to Node.js or Deno,


JavaScript can be executed outside of the browser too. the code then
executes directly on the machine .

3. On Mobile Devices (e.g. via embedded websites) : with extra technologies


like Capacitor or React Native, you can build mobile apps based on
JavaScript. The code then executes on the mobile device.

How to add JavaScript to a website:

1. Between <script> tags:


not advised to use it because:

1. Can quickly lead to unmaintainable & complex HTML files.

2. Typically only used for very short scripts.

React - The Complete Guide 2024: 7


<script>alert("hello!")</script>

2. via <script> import:

<script src="js.script.js"></script>

the keyword defer insures that the JavaScript code will only be executed only
after the rest of the HTML document has been read and parsed.

the type = “module” attribute in the script tag makes sure that this JS file is treated
as a JavaScript module. which unlocks the import syntax where you can import
code from script A into script B.

when working with react you’ll almost never add these script tags to your
html file on your own because react project almost always use a build process
which as part of this process injects these scripts tags in the code for you.
what does build process mean ? ⇒ it means that the code you write is not the
code that gets executed (like this ) in the browser, instead, the code is
transformed before its handed off to the browser.

the reasons on why we use build process :

1. Raw, unprocessed React code won’t execute in the browser, because


JSX is not a default JavaScript feature.

2. the code would not be optimized for production (e.g. not minified
[minification ⇒ names of variables or functions are shortened to
reduce the amount of JS code that is served to the user] ).

import & export:


in order for this to work you need to set the type = “module” when using vanilla JS

//export a var
export const variableName = "i am a variable";
//importing syntax

React - The Complete Guide 2024: 8


import { variableName } from "./location.js"

//export a default value


export default "this is a default export";
//importing a default
import naming_the_value from './location.js';

//exporting multiple vars


export const var1 = "i am number 1";
export const var2 = "i am number 2";
export const var3 = "i am number 3";

//importing multiple vars


import { var1, var2, var3 } from './location.js';

//importing multiple vars as a JS group (object)


import * as varsName from './locations.js';

Variables and Values:

Data Types:

React - The Complete Guide 2024: 9


Variables store values:
Variables are data container. and they are used to offer:

1. Readability ⇒ Organize your code over several lines rather than


cramming everything into a single line.

2. Re-usability ⇒ store a value in a variable once and reuse it as often


and in many places as needed.

Variables are declared using the keywords:

1. let

2. var

3. const

let userMessage = "Why ?? my value can be re-assigned";


var x = "my value is x";
const y = "i cannot be re-assigned";

console.log(userMessage );
console.log(x);
console.log(y);

Operators:

// Operators
console.log(6 + 2);
console.log("text 1 " + " ,Text 2"); //string concatenation
console.log(6 - 2);
console.log(6 / 2);
console.log(6 * 2);
console.log(6 % 2);
console.log(6 ^ 2);

// comparison operators

React - The Complete Guide 2024: 10


console.log(6 === 2); //strictly equal
console.log(6 > 2);
console.log(6 < 2);
console.log(6 >= 2);
console.log(6 <= 2);
console.log(6 !== 2);

Functions & Parameters:

// declaring the function using function keyword


function greet(name) {
console.log("Hello,",name)
}
// invoking the function
greet("Dan");

// you can assign a default value to a parameter like this


function greetings(userName, msg = "Hello!!!") {
//console.log(userName);
//console.log(msg);
return "Hi, iam " +userName +". " +msg;

}
//this works without the return statement
greetings("Dan");
greetings("Sam", "how u doin ?");

//works with the return statement


const maxGreetings = greetings("Sam", "how u doin ?");
console.log(maxGreetings);

NOTE !!! ⇒ functions must only have ONE return statement at most.
Functions without “return ” implicitly return “undefined”.

React - The Complete Guide 2024: 11


Arrow Functions(best when dealing with anonymous functions that don’t need
a name):

// - using the function keyword


export default function () {
console.log("Hello !");
};
// arrow syntax
const sum = (num1, num2) => {
return num1 +" + " +num2 +" = " +(num1+num2);
}
console.log(sum(3,2));

Objects and Classes:

objects are used to group values together with key-value pairs. and is
created by using {}

classes : are blueprints for an object.

Array & Array methods:

an array is a special type of object and are created using [] and contains
a list of values. and the idea is to have just values in a certain order which
can be accessed by their position in that list.

arrays can contain all sorts of values, for e.g. another array, objects, string
etc…

// Arrays & Array methods:


const hobbies = ["playing chess", "reading", "drawing"];
console.log(hobbies);
console.log(hobbies[0]); //playing chess
console.log(hobbies[1]); //reading
console.log(hobbies[2]); //drawing

array Methods:

React - The Complete Guide 2024: 12


a. array.findIndex() this method takes a function as its parameter.

const index = hobbies.findIndex((item) => item === "sports");


console.log(index); //-1 : dosent exist

b. array.map() : allows you to transform every item in the array to another


item. and takes a function as an input.
⇒⇒ map will return a new array with the transformed values.

const arr2 = hobbies.map((item) => item + "!");


console.log(arr2);

// you can use map to transform the type for e.g. from string to object
const objectArr = hobbies.map((item) => ({text: item}));
console.log(objectArr);

de-structuring :
instead of creating variables from an array like this:

const userNameData = ["Dan", "Vashappening"];

const firstName = userNameData[0];


const lastName = userNameData[1];

by using de-structuring we can do it like this:

const [firstName, lastName] = ["Dan", "Vashappening"];

console.log(firstName);
console.log(lastName);

this approach can also be used with objects

const user = {
name: "Dan",

React - The Complete Guide 2024: 13


age: 22
};
const name = user.name;
const age = user.age;

//with destructuring
const {name, age} = user;

⇒⇒ NOTE!!!: when de-structuring an object we have to use the same


property name as the object, however, we don’t have to when de-
structuring an array.
well u could assign an alias as follows:

const {name: userName, age: userAge} = user;


console.log(userName);

Primitive Values and Reference values:

React - The Complete Guide 2024: 14


React course:
module 03: React basics working with components:

Components: are reusable UI building blocks that we create and then combine
to create the interactive user interface.

any website can be broken down into smaller building blocks: Components, it
can therefore also be built by creating & combining such components.

the idea behind creating a component is that they wrap HTML and possibly
CSS code as well as any JavaScript logic that might be needed and together
those languages and code pieces then define and control a part of the UI.

React - The Complete Guide 2024: 15


why this Component approach is so powerful and popular ?

1. Reusable Building Blocks:

create small building blocks & compose the UI from them.


⇒ if needed: Reuse a building block in different parts of the UI (e.g., a
reusable button).

2. Related code lives Together:

Related HTML & JS (possibly some CSS) code is stored together.

since JS influences the output, storing JS + HTML together makes


sense.

3. Separation of Concerns:

Different components handle different data & logic.

Vastly simplifies the process on working on complex apps.

React - The Complete Guide 2024: 16


Different Components, Different Responsibility.

React - The Complete Guide 2024: 17

You might also like