Lec 3
Lec 3
1
Function Declarations and Arrow Functions
◦ function keyword vs. () => {…}
Template Literals
◦ + operator to add each string segment to one another
vs. two back ticks `` instead of single or double quotes
Short Conditionals &&, ||, Ternary Operator
◦ &&, ||, and Ternary Operator
The Three Array Methods:
◦ .map(), .filter(), and .reduce()
Object Tricks
◦ Property Shorthand, Destructuring, and Spread Operator
Promises + Async/Await Syntax
2
In React, components are defined with both
JavaScript functions and classes
React components return JSX elements that are used
to structure our application interface
React functions named in Pascal Casing, while
JavaScript functions named in Camel Casing
3
There are two different ways to write a function in
JavaScript
◦ Function declaration: The traditional way, using the function
keyword
◦ Arrow function: A shorthand way that was introduced in ES6
// Function declaration syntax
function MyComponent(props) {
return <div>{props.content}</div>;
}
// Arrow function syntax
const MyComponent = (props) => {
return <div>{props.content}</div>;
};
// Arrow function syntax (shorthand)
const MyComponent = (props) => <div>{props.content}</div>;
4
One small benefit of using function declarations over
arrow functions is that you don't have to worry about
problems with hoisting
◦ Hoisting is JavaScript's default behavior of moving all
declarations to the top of the current scope
◦ Arrow function components must be declared before used
function App() {
return (
<>
{/* Valid: FunctionDeclaration is hoisted */}
<FunctionDeclaration />
{/* Invalid: ArrowFunction is NOT hoisted. Therefore, it must be
declared before it is used */}
<ArrowFunction />
</>
);
}
function FunctionDeclaration() { return <div>Hello React!</div>;}
function ArrowFunction() { return <div>Hello React, again!</div>;}
5
If you want to concatenate multiple strings together,
you needed to use the + operator to add each string
segment to one another
With the addition of ES6, we were given a newer form
of string called a template literal:
◦ Consists of two back ticks `` instead of single or double
quotes
◦ Instead of having to use the + operator, we can connect
strings by putting a JavaScript expression within a special ${}
syntax:
function sayHello(text) {
return "Hello " + text + "!";
}
function sayHelloAgain(text) {
return `Hello again, ${text}!`;
}
6
Considering that React is just JavaScript, it is very
easy to conditionally show (or hide) JSX elements:
function App() {
const isLoggedIn = true;
if (isLoggedIn) {
// Shows: Welcome back!
return <div>Welcome back!</div>;
}
return <div>Who are you?</div>;
We can transform the if statement above into the
following, using the ternary operator. :
// Shows: Welcome back!
return isLoggedIn ? <div>Welcome back!</div> : <div>Who are you?</div>;
// Or Ternary operators can also be used inside curly braces
return <div>{isLoggedIn ? "Welcome back!" : "Who are you?"}</div>;
// Or
// If true: Welcome back!, if false: nothing
return <div>{isLoggedIn && "Welcome back!"}</div>;
7
.map(): Iterates over an array to show each array element
within an individual JSX element:
function App() {
const programmers = ["Reed", "John", "Jane"];
return (
<ul>
{programmers.map( (programmer) => (
<li>{programmer}</li>
))}
</ul>
);
}
.filter(): Filters certain elements out of array:
function App() {
return (
<ul>
{/* Returns 'Reed' */}
{programmers
.filter((programmer) => !programmer.startsWith("J"))
.map((programmer) => (
<li>{programmer}</li>
))}
</ul>
);
8
.reduce(): is capable of transforming array values into
virtually any data type, even non-array values:
function App() {
const programmers = ["Reed", "John", "Jane"];
return (
<ul>
{/* Returns 'Reed' */}
{programmers
.reduce((acc, programmer) => {
if (!programmer.startsWith("J")) {
return acc.concat(programmer);
} else {
return acc;
}
}, [])
.map((programmer) => (
<li>{programmer}</li>
))}
</ul>
);
9
Property Shorthand:
const name = "Reed";
const user = {
// instead of name: name, we can use...
name,
};
console.log(user.name); // Reed
Destructuring:
const user = {
name: "Reed", age: 28, isEnglishSpeaker: true,
};
// Dot property access
const name = user.name;
const age = user.age;
// Object destructuring
const { age, name, isEnglishSpeaker: knowsEnglish } = user;
10
Spread Operator:
◦ Instead of copying properties manually, you can spread all
of an object's properties into another object (as you create
it) using the object spread operator:
const user = {
name: "Reed", age: 28, isEnglishSpeaker: true,
};
const firstUser = {
name: user.name,
age: user.age,
isEnglishSpeaker: user.isEnglishSpeaker,
};
// Copy all of user's properties into secondUser
const secondUser = {
...user,
};
11
Virtually every React application consists of
asynchronous code
Promises are used to resolve asynchronous code
to make it resolve like normal, synchronous
code, which we can read from top to bottom
Promises traditionally use callbacks to resolve
our asynchronous code
◦ We use the .then() callback to resolve successfully
resolved promises
◦ we use the .catch() callback to resolve promises that
respond with an error
12
13
14
Lets you synchronize a component with an external system
◦ useEffect(setup, dependencies?)
◦ Call useEffect at the top level of your component to declare an
Effect:
// 1. Import *useState* and *useEffect*
import React, {useState, useEffect} from 'react';
import './App.css';
function App() {
// 2. Create *dogImage* variable as well as the *setDogImage* function via useState
let [dogImage, setDogImage] = useState(null)
// 3. Create out useEffect function
useEffect(() => {
fetch("https://dog.ceo/api/breeds/image/random")
.then(response => response.json())
// 4. Setting *dogImage* to the image url that we received from the response above
.then(data => setDogImage(data.message))
},[])
return (
<div className="App">
{/* 5. Using *dogImage as* the *src* for our image*/}
{dogImage && <img src={dogImage}></img>}
</div>
);
}
15
An example of using React to fetch data from Fake
API using the Fetch API to show profile image
◦ The data is resolved using promises:
const App = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
/*
The first .then() gets JSON data from the response
The second .then() gets the url to avatar and puts it in state
*/
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => setPosts(data))
.catch((error) => console.error("Error fetching data: ", error));
}, []);
return <ul>
{posts.map( (post) => (
<li>{post.title}</li>
))}
</ul>
};
16
Instead of always needing to use callbacks to resolve our
data from a promise
◦ Use a cleaned syntax that looks identical to synchronous code,
called the async/await syntax:
const App = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
async function fetchPosts() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
setPosts(data);
}
fetchPosts();
}, []);
return
<ul>
{posts.map( (post) => (
<li>{post.title}</li>
))}
</ul>
};
17