Basic
- JSX
- Components
- Class component
- Function component
- Importing a component
- Var Let Const
- Array
- Object
- Arrow Function
- Array.map Method
- Array.concat Method
- Destructuring
- Class
- Inheritance
- Modules
JSX
- JSX expressions look like simple html, but has the full power of Javascript
const element = <h1>Hello, world!</h1>;
- JSX is a syntax extension to JavaScript
- JSX describe what the UI should look like
- You can put any valid JavaScript expression inside the curly braces in JSX
- uses camelCase property naming convention eg. myElement
const name = 'Josh Perez';
const myElement = <h1>Hello, {name}</h1>;
Components
- Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
- They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
- Components come in two types, Class components and Function components
- typically defined in Pascal-case naming convention eg. MyComponent
Class component
- A class component must include the extends React.Component statement. This statement creates an inheritance to React.Component, and gives your component access to React.Component's functions.
- The component also requires a render() method, this method returns JSX.
import React,{ Component } from 'react';
class MyCar extends React.Component {
render() {
return <h2>Hi, I am a car!</h2>;
}
}
export default MyCar;
Function component
- A Function component also returns JSX, and behaves much the same way as a Class component, but Function components can be written using much less code
import React,{ Component } from 'react';
function MyCar() {
return <h2>Hi, I am a car!</h2>;
}
export default MyCar;
Importing a component
- inside index.js, import the component
import React,{ Component } from 'react';
import ReactDOM from 'react-dom';
import MyCar from './components/MyCar'; //Import component so that we can use it
ReactDOM.render(<Car />, document.getElementById('root'));
Var Let Const
- Var:declarations are globally scoped
- Const and Let:declarations are block scoped
Array
- a type of variable that can contain list of values or objects
- has methods to perform traversal and mutation operations.
let fruits = []; //create an empty array
let fruits = ['Apple', 'Banana']; //create an array with default items
fruits[0] = 'Watermelon'; //insert/replace an item
let first = fruits[0]; //access the first item in array
let last = fruits[fruits.length-1]; //access the last item in array
fruits.forEach(function(item, index, array) { //loop through an array
console.log(item, index);
})
for (let i = 0; i < fruits.length; i++){ //loop through an array
console.log(fruits[i], i);
}
fruits.push('Orange'); //Add an item to the end of an Array
fruits.pop(); //Remove an item at the end of an Array
fruits.unshift('Strawberry'); //Add an item at the beginning of an Array
fruits.shift(); //Remove an item at the beginning of an Array
fruits.indexOf('Banana'); //Find the index of an item
fruits.splice(3, 1); //Remove 1 item at index position 3 (index starts at 0)
fruits.splice(3, 2); //Remove 2 items at index position 3 (index starts at 0)
let myClone = [...fruits]; //clone an array
let myClone = Array.from(fruits);//clone an array
let myClone = fruits.slice(); //clone an array
//combining 2 arrays
const first = [1,2,3];
const second = [4,5,6];
const combined = first.concat(second); //concat method
const combined = [...first, ...second]; //spread operator
Object
- a type of variable that can contain collection of key/value pairs that can be modified throughout the lifecycle
- Objects allow us to define custom data types in JavaScript
- typically defined in camel-case styling
let user = { //declaring an object
firstName:"Peter",
lastName:"Chan",
fullName:function(){return this.firstname + " " + this.lastName;} //ES5's method for an object literal, must specify the name and definition of a complete function
fullName(){return this.firstname + " " + this.lastName;} //ES6 uses shorthand syntax
}
user['gender']='male'; //add a key/value pair
user['firstName'] = 'James'; //replace a key/value pair
user.lastName = 'Franco'; //replace a key/value pair
delete user.lastName; //delete a key/value pair
let myClone = {...user}; //clone an object
//combining 2 objects
let obj1 = {1 : "Hello", 2: "World"};
let obj2 = {3 : "Welcome", 4: "Back"};
let final_obj = Object.assign(obj1, obj2); //assign operator
let new_obj = {...obj1, ...obj2}; //spread operator
Arrow Function
- Arrow functions were introduced in ES6
- Arrow functions allow us to write shorter function syntax
const hello = function() { //before
return "Hello World!";
}
const hello = () => { //can be rewritten as an arrow function like this
return "Hello World!";
}
const hello = () => "Hello World!"; //or even simpler
Array.map Method
- The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array1 = [1, 4, 9, 16];
// pass a function to map
const doubled = array1.map(x => x * 2);
console.log(doubled);
// expected output: Array [2, 8, 18, 32]
//map is useful to render lists of items
const colors=["red","green","blue"];
const items = colors.map(color => `${color}`);
console.log(items);
//this will return <li>red</li> <li>green</li> <li>blue</li>
Array.concat Method
- creates a new array that is populated with the result of merging 2 or more arrays
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]
Array.filter Method
creates a new array with all elements that pass the test implemented by the provided function.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Destructuring
- a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
//array destructuring
let myarray = ["John", "Smith"]
let [firstname, surname] = myarray;
//object destructuring
let myobject = {title: "Menu",width: 100,height: 200};
let {title, width, height} = myobject;
Class
- Classes are a template for creating objects
- They encapsulate data with code to work on that data.
- So that we can change the implementation in one place when the need arises
- use Pascal naming convention (first letter Capitalize)
class Rectangle { //create a class (blueprint)
constructor(height, width) {
this.height = height;
this.width = width;
}
getArea(){
return height*width;
}
}
const myTable = new Rectangle(150,200); //instantiate a new object based on class
myTable.getArea();
Inheritance
- A class created with a class inheritance inherits all properties and methods
class Person{ //create a class
constructor(name){
this.name = name;
}
walk(){
console.log('walk');
}
}
class Teacher extends Person { //use the extends keyword to inherit from another class
constructor(name, degree){
super(name); //MUST call super's constructor first
this.degree = degree; //THEN define own constructor
}
teach(){
console.log('teach');
}
}
Modules
- providing mechanisms for splitting JavaScript programs up into separate modules that can be imported when needed
- save the following in a file called person.js
export default class Person{
constructor(name){
this.name = name;
}
walk(){
console.log('walk');
}
}
- save the following in a file called teacher.js
import Person from './person';
export default class Teacher extends Person {
constructor(name, degree){
super(name);
this.degree = degree;
}
teach(){
console.log('teach');
}
}
-finally in index.js
import Teacher from './teacher';
const teacher = new Teacher("Peter","Master's Degree");
teacher.teach();