0% found this document useful (0 votes)
44 views59 pages

Week 3 Basics-2

React

Uploaded by

esraravensburg
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)
44 views59 pages

Week 3 Basics-2

React

Uploaded by

esraravensburg
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/ 59

1

React
Basics-2

CENG 475
2
JavaScript

In case it’s been some time since you last worked with JavaScript
 Core Syntax & Rules Essential,
 Modern JavaScript Features
 Key JavaScript Features Used In React Apps

CENG 475
3 JavaScript Can Be Executed In
Many Environments

In the Browser On any Computer (e.g, On mobile Devices


(i.e., as part of server-side code) (e.g., via embedded
websites) websites)

JavaScript code can be Thanks to Node.js or Deno, With extra technologies like
included in any website JavaScript code can be Capacitor or React Native,
The code then executes executed outside of the you can build mobile apps
inside the browser (i.e., on browser, too based on JavaScript
the machine of the website The code then executes The code then executes on
visitor) directly on the machine the mobile device

CENG 475
4 Adding JavaScript Code To A Website

Between <script> Tags Via <script> Import

<script>
<script src=“script.js”>
alert('Hello')
</script>
</script>

Can quickly lead to Separates HTML &


unmaintainable & complex JavaScript code,
HTML files. Maintaining complex
Typically only used for very JSpowered
short scripts apps becomes easier

CENG 475
5 JavaScript Code Consists Of
“Statements”
Statement

The “thing” that gets executed

Values /
Keywords Identifiers
Expressions
Built into JavaScript Defined by Defined by developers
let, if, for, … developers Used to Hardcoded values or
Required to “tell” identify commands expressions that
JavaScript that a (functions), produce new values
certain feature is variables (values)
used etc. ‘Hello world’, 5 - 3, …
alert(), age, …
CENG 475 let, if, for, …
6
Keywords
Keywords enable language features

let, const, if, for, function, …

CENG 475
7
Identifiers

• Variables,
• Functions (“Commands”)
• Parameters
• Property

JavaScript code is case-sensitive!

CENG 475
8
React Projects

React projects use a build process


The code you write is not the code that gets
executed (like this) in the browser,
Instead;
Your code is transformed before it’s handed off to
the browser

CENG 475
"name": "week2",
"version": "0.1.0",
"private": true,

React Projects
"dependencies": {
9 "@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
package.json "scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
lists all the dependencies "test": "react-scripts test",
"eject": "react-scripts eject"
},
of the code "eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
CENG 475 } }
10
React Projects
1. Raw, unprocessed React code won’t execute in the
browser
JSX
JSX is not a default JavaScript feature

<div> Hello </div>;

Will not work in App.js


JSX codes must transformed by developer server
installed locally
CENG 475
11
React Projects

2. In addition, the code would not be optimized for


production (e.g., not minified, means that shortened names of
functions var to get shorter form of JS)

• React projects require a build process that transforms your


code
create-react-app, vite etc. give you such a build process (no custom setup or
tweaking needed)

CENG 475
12 React ES6

What is ES6?
 ES6 stands for ECMAScript 6.
 ECMAScript was created to standardize JavaScript, and ES6 is
the 6th version of ECMAScript, it was published in 2015, and is
also known as ECMAScript 2015.

CENG 475
13 Why Should I Learn ES6?
React uses ES6, and you should be familiar with some of
the new features like:
❑ Classes
❑ Arrow Functions
❑ Variables (let, const, var)
❑ Array Methods like .map()
❑ Destructuring
❑ Modules
❑ Ternary Operator
❑ Spread Operator
CENG 475
14 How to Use ES6 Modules?
Modules help you split various functionalities of your app
into separate files/scripts. You can have different scripts
for form validation, logging a user in, and so on.

This is the structure of our folder:


❑ index.html
❑ script.js
❑ myModules/
❑ add.js
❑ sub.js
CENG 475
15 Step 1 – Create the HTML file and link
your script
<html>
<head>
<title>JavaScript Refresher</title>
<link rel="stylesheet" href="assets/styles/main.css" />
<meta charset="UTF-8" />
<script src="assets/scripts/app.js" type="module"></script>
</head>

CENG 475
16 Step 2 – Create and export functions
into separate files
Here's the function for addition in “src="assets/scripts/app.js"

To be able to use these functions in other scripts, you have to


export them by adding the export statement.

CENG 475
17 Step 3 – Import the functions into
script.js
app.js;

import { apiKey } from "./util.js";

util.js;
export default "adnasdoasflak1";
export let apiKey = "adnasdoasflak1";
export let abc = "abc";

CENG 475
18
Import & export
Since there is no build process, we need a web server working
at some place, locally perhaps

There are 2 solutions for a live server;

CENG 475
19
Import & export
1st solution with
VS Code
Extensions

Extensions

Local developer server;


CENG 475
http://127.0.0.1:5500/
20
Import & export
1st solution with VS Code, port 5500

To stop;
Alt L + Alt C,

And try other key


combinations using F1

To restart server;
Alt L + Alt C

Or write to F1 and select


your choice
CENG 475
21
Import & export
2nd solution: Since there is no build process, we need a web server
working at some place, locally perhaps thru node, this time port is
8080

So run in the Command prompt;


➢ npx live-server

Local developer server;


http://127.0.0.1:8080/

To stop or Exit:
CTRL+C
CENG 475
22
Import & export

Check console

CENG 475
23
Import & export
<head>
<title>JavaScript Refresher</title>
<link rel="stylesheet" href="assets/styles/main.css" />
<meta charset="UTF-8" />
<script src="assets/scripts/app.js" type="module"></script>
</head>

app.js;
import { apiKey } from "./util.js";

Pay attention
Your have to write with full name: *.js
CENG 475
24
ES6 Modules
Export is ES6's feature which is used to Export a module(file) and
use it in some other module(file).

Default Export:
1.default export is the convention if you want to export only
one object(variable, function, class) from the file(module).
2.There could be only one default export per file, but not
restricted to only one export(Named export).
3.When importing default exported object we can rename it as
well.

CENG 475
25
ES6 Modules
2. Export or Named Export:

1. It is used to export the object(variable, function, class) with


the same name.

2. It is used to export multiple objects from one file.

3. It cannot be renamed when importing in another file, it must


have the same name that was used to export it, but we can
create its alias by using as operator.

CENG 475
26 Exports & Imports
There are two different types of exports: default (unnamed) and
namedexports

default => export default ...;


named => export const someData = ...;

default exports like below (without {})

import someNameOfYourChoice from './path/to/file.js';


Named exports have to be imported by their name (with {})
import { someData } from './path/to/file.js’;
named exports at once with the following syntax
import * as upToYou from './path/to/file.js';
CENG 475
27 React Fundamentals

let & const

let and const basically replace var . You use let


instead of var and const instead of var if you plan
on never re-assigning this "variable" (effectively
turning it into a constant therefore).

CENG 475
28 React Fundamentals

a) export default "defaultExport";


b) export let apiKey = "test1";
c) export let apiKey1 = "test2";
d) export let abc = "abc";

export default in (a) is possible once for


each file, for multiple you will use (b-d)

Note: For (a);


import apiKey from "./util.js"; //week3_1-11
CENG 475
29 React Fundamentals

You can use:


import { apiKey, abc as content } from "./util.js";

Instead:
import * as util from "./util.js";
Where util is an object, name is up to you.

console.log() can be used as


console.log(apiKey); printf in C/C++
CENG 475
30 There Are Different Types Of Values
String Number Boolean Null & undefined

Positive or negative True or false “There is no value”


Text values Wrapped
With decimal point A simple “Yes” or undefined: Default if no
with single or double
(float) “No” value was assigned yet
quotes
or without it value type null: Explicitly assigned
Can also be created
(integer) Typically used in by
with backticks (`)
conditions developer (reset value)
5
"Hello World"
-23 true undefined
'Max' `Hi
3.14 false null
there`
-8.12

CENG 475
Additionally Objects
31
Variables
Variables store Values

“Hi everyone!” Value (Type: String)

A variable stores a value

Variable

userMessage Variable Identifier

CENG 475
32
Why Use Variables?
1 2

Reusability Readability

Store a value in a variable Organize your code over


once and use it as often and several lines rather than
in as many places as needed cramming everything into a
single line

CENG 475
33 Identifiers Must Follow Certain Rules
& Recommendations
1. Must not contain whitespace or special characters (except $ and _)
Valid: $userName, age, user_name, data$, …
Invalid: %userName, age/, user name, …

2. May contain numbers but must not start with a number


Valid: user3, us3r, …
Invalid: 3user, 11players, …

3. Must not clash with reserved keywords


Valid: user, age, data, …
Invalid: let, const, if, …
CENG 475
34 Identifiers Must Follow Certain Rules
& Recommendations
4. Should use camelCasing
Recommended: userName, isCorrect, …
Uncommon: user_name, iscorrect, …

5. Should describe what the “thing” it identifies contains or does


Recommended: userName, isCorrect, loadData, …
Uncommon: userDataPoint, correctness, dataLoader, …

CENG 475
35
Variables vs Constants

Variables Constants

Defined via let Defined via const


Can be re-assigned Cannot be re-
(i.e., the stored value assigned (i.e., the
can be overwritten) stored value can’t
be overwritten)
let age = 34;
age = 29; const age = 34;
age = 29;

Allowed Error

CENG 475
36
Variables vs Constants

Variables Constants

const userMessage = "Hello World!!!";

console.log(userMessage);
console.log(userMessage+' CENG 475“’);

//single & double quotation marks

//code_03_13-18

CENG 475
37
Variables vs Constants
Values can be hardcoded
But they can also be derived via
Expressions & Operators

const userMessage = "Hello World!!!";

//console.log(userMessage);
console.log(userMessage+" CENG 475");
console.log(10 =='10’) //type equivalence

All operators work as usual JS


CENG 475
38 Identifiers Must Follow Certain Rules
& Recommendations

Semicolons are optional (in most cases)!

Whitespace is ignored in many cases!

Use it to format your code & improve readability But


avoid adding too much whitespace

CENG 475
39 React Fundamentals

Arrow function expressions


An arrow function expression is a compact alternative to a
traditional function expression, with some semantic differences and
deliberate limitations in usage:
•Arrow functions don't have their own bindings to this, arguments,
or super, and should not be used as methods.
•Arrow functions cannot be used as constructors. Calling them
with new throws a TypeError. They also don't have access to
the new.target keyword.
•Arrow functions cannot use yield within their body and cannot be created
as generator functions.
CENG 475
40 React Fundamentals

ES6 Arrow Functions

Arrow functions are a different way of creating functions in


JavaScript. Besides a shorter syntax, they offer
advantages when it comes to keeping the scope of the
this keyword.

Arrow function syntax may look strange but it's actually


simple.

CENG 475
41 ES6 Arrow Functions
Anonymous functions are without names
function() {
// Function Body
}

OR,
Using function keyword or
( () => {
Arrow function notation
// Function Body...
} )();

OR,

CENG 475
42 ES6 Arrow Functions
var greet = () => {
console.log("Welcome to CENG 475! \nIs it cool?");
};
//code_03_21-41
greet();

function createGreeting(userName, message = "Hello!") {


console.log(userName);
console.log(message);
return "Hi, I am " + userName + ". " + message;
}

const greeting1 = createGreeting("Student1 ");


console.log(greeting1);

const greeting2 = ("Student1", "Hello, what's up?");


console.log(greeting2);
CENG 475
43 ES6 Arrow Functions
Anonymous functions are without names
function() {
// Function Body
}

OR,
Using function keyword or
( () => {
Arrow function notation
// Function Body...
} )();

OR,
CENG 475
44 ES6 Arrow Functions
Then working with Arrow Functions, you have a couple
of "syntax shortcuts" available.
Most importantly, you should know about the following
alternatives:
1) Omitting parameter list parentheses
If your arrow functions takes exactly one parameter, you
may omit the wrapping parentheses.

CENG 475
45 ES6 Arrow Functions
function callMe(name) {
console.log(name);
}

which you could also write as:


const callMe = function(name) {
console.log(name);
}
becomes:
const callMe = (name) => {
console.log(name);
}

CENG 475
46 ES6 Arrow Functions

Ex 1:
function createGreeting(userName, message = "Hello!") {
console.log(userName);
console.log(message);
return "Hi, I am " + userName + ". " + message;
}

Ex 2:
function createGreeting(userName, message = "Hello!") {
return "Hi, I am " + userName + ". " + message;
}
const greeting1 = createGreeting("Ender ");
console.log(greeting1);

CENG 475
47 ES6 Arrow Functions ( ()=> )

The function is then stored in the greet variable. We can call the function by
invoking greet().

var greet = function () {


console.log("Welcome to CENG 475!");
};

greet();

we pass arguments to the anonymous function

var greet = function (platform) {


console.log("Welcome to ", platform);
};

greet(" CENG 475!");


CENG 475
48 ES6 Arrow Functions ( ()=> )

A self-executing function.
(function () {
console.log("Welcome to CENG 475!");
})();

The use of arrow function.


var greet = () =>
{
console.log("Welcome to CENG 475!");
}
greet();
OR final self-executing function in another way;

let greet = () => console.log("Welcome to CENG 475!");


greet();
CENG 475
49 Arrays
const hobbies = ["Sports",
"Cooking", "Reading"];
console.log(hobbies[0]);

You can see array utility methods


by after putting a dot after the
name of the array.

This is a good capability of MS


tools.

//code_03_44-54
CENG 475
50 Arrays
Ex 3: //code_03_44-54

Array push method:


const hobbies = ["Sports", "Cooking", "Reading"];
console.log(hobbies[0]);
console.log(hobbies[1], typeof (hobbies[3]));
hobbies.push(-4.003);

Ex 4:
findIndex method needs a function
const index1 = hobbies.findIndex("a");
const index = hobbies.findIndex((item) =>
{ return item == "32.04" });

Get rid of return statement and {}


CENG 475
51 Arrays
Array.Map function:

Array.map method takes a function as its argument. This


function will be invoked once for every item in the array, and
whatever it returns will be added to the new array:
const highSchools = school.map(school => `${school} High
School`);
// Cumhuriyet High School
// Anatolian High School
//code_3_57-72
// Gazi High School

Note: Original array remains unchanged.


See in the code Ex 5 (pay attention to arrow function):

CENG 475
const editedHobbies1 = hobbies.map((item) => (" ! "+item));
52 Arrays
Array.Map function is used for transforming any array item to any
other item.
Let’s do not change strings, and create JS objects by {}
We have to warp it with (), tell JS {} do not define the function body

The map function can produce an array of objects, values, arrays,


other functions—any JavaScript type. See the map function
returning an object for every school:
const highSchools = schools.map(school => ({ name: school }));
console.log(highSchools);
// [
// { name: " Cumhuriyet" },
// { name: " Anatolian" },
// { name: “Gazi" }
CENG 475 // ]
53 Arrays
const editedHobbies = hobbies.map((item) => ({ text: item }));

Object

In that object, text is up to you, item is every item in the array

Let’ see the console


in VS Code.

//code_3_74-80

CENG 475
54 Arrays
//code_3_83-90
Exam Question: Array Methods
Write a transformToObjects() function that should transform a list of
numbers into a list of JavaScript objects.

In the newly returned array, every object must have a val key and
the input array's number as a value.

For example, for the provided input [1, 2, 3 ] the


transformToObjects ([1, 2, 3]) function should return

[{val: 1}, {val: 2}, {val: 3}]. //code_3_91-100

CENG 475
55 Array map() function
Go to week2 src_209

How does the map function work?


The map JavaScript function creates a new array from the results
of the provided callback function.
This callback function gets called for each element of the array.

A small example:

//code_209_03-17

CENG 475
56 Array map() function
const shoppingList = ['Oranges', 'Cassava', 'Garri', 'Ewa', 'Dodo',
'Books'];
export default function a(){

return (
shoppingList.map((item, index) => {
return (
<ol>
<li key={index}>{item}</li>
</ol>
)
})

)
}
//code_209_03-17

CENG 475
57 Array map() function

How to map over an array of objects in React?


To render a list of components from an array of objects in
React, you have two options:
• Use the map function
• Use a loop or the forEach function

•Here is an example of mapping over an array of objects:

//code_209_23-33

CENG 475
58 Array map() function
const array = [
{
name: "Tim",
age: 27
},
{
name: "Bob",
age: 32
}
];
export default function App() {
return (
<div>
{array.map((item, index) => (
<div key={index}>
<div>Name: {item.name}</div>
<div>Age: {item.age}</div>
</div>
))} //code_209_23-48
</div>
)
CENG 475 }
59 Array map() function: A complex example
const employeesData = [
{
name: 'Saka manje',
address: '14, cassava-garri-ewa street',
attributes: {
height: '6ft',
hairColor: 'Brown',
eye: 'Black',
},
gender: 'Male',
},
{
name: 'Adrian Toromagbe',
address: '14, kogbagidi street',
attributes: {
height: '5ft',
hairColor: 'Black',
eye: 'Red',
}, //code_209_49-94
gender: 'Male',
},
CENG 475 ]

You might also like