SlideShare a Scribd company logo
Sergio Nakamura | nakamurasei.com hi@nakamurasei.com
An Introduction
To React For
Frontend Developers
An Introduction To React For Frontend Developers hi@nakamurasei.com
Disclaimer
Many of the techniques displayed aren’t exclusive to React. In fact, React is
built in JavaScript and as such all React features can be implemented in
JavaScript (and have existed for years, albeit with less flashy names).
However React offers a “framework”, a structure you can use to build your
applications. While not many people will implement a pub-sub method or a
helper method to simplify element creation, many people will use a
framework. You can use its features without knowing its inner workings,
without reinventing the wheel, and using the same conventions.
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
JavaScript has been used for over two decades to add interactivity to
webpages: adding, removing or modifying elements, responding to user
input and sending and receiving data from external sources.
React (just like Angular, Vue and many more) are frameworks built on
JavaScript that allow easier development of user interfaces.
1.
Declarative
Style
2.
Automatic
Updates
3.
Virtual
DOM
4.
Modular
Structure
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Declarative Style
If you’ve previously used JavaScript you may have found yourself telling the
browser each step to make: select X element, set the content to Y, do Z
when clicked... Having to tell each step can be classified as an
“Imperative” style: forgetting a step may lead to errors, because the browser
just follows instructions, it doesn’t know what you’re actually looking for.
In React, you are following most of the time a “Declarative” style, you tell
what you want and provide the data. React does the work behind the
scenes to translate that information to the instructions your browser
understands.
1
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Declarative Style
Let’s render a <button> and console.log when clicked, in Vanilla JS and React.
Vanilla JS React JS
1
const btn =
document.createElement(“button”);
//Create <button>
body.appendChild(btn); //Append to body
btn.innerText = “Click me”; //Change text
btn.addEventListener(“click”, () => {
console.log(“Clicked”);
}); //Log “Clicked” when clicked
import React from “react”;
export default function App() {
return (
<button onClick={() =>
console.log(“Clicked”)}>
Click me
</button>
);
} //I want a <button> with “Click me” as
text that logs “Clicked” when clicked
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Automatic Updates
As your application grows adding an element and setting a value isn’t
enough: you may need to update its content as you receive new
information.
Without a framework as React, you may have to tell the browser to update the
elements every time we receive new information. While this doesn’t seem a
big deal at first it can get ugly fast.
Using React, all the elements depending on a piece of data get updated
automatically when the data changes.
2
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Automatic Updates
Let’s see a simple button that +1 to a counter. The counter variable is seen in
two places at the time.
2
Vanilla JS React JS
let counter = 0; //Counter
const p = document.createElement(“p”); //Create a <p>
p.innerText = counter; //Set <p>’s text
body.appendChild(p); //Append <p> to the body
const btn = document.createElement(“button”);
//Create a <button>
btn.innerText = `+1 and make it ${counter + 1}`;
//Set <button>’s text
body.appendChild(btn);
//Append <button> to the body
btn.addEventListener(“click”, () => {
counter = counter ++; //Update the counter
p.innerText = counter; //Update <p>
btn.innerText = `+1 and make it ${counter + 1}`;
// Update <btn>
})
import React, {useState} from “react”;
export default function App() {
const [counter, setCounter] = useState(0);
return (<div>
<p>{counter}</p>
<button onClick={() =>
setCounter(counter++)}>
`+1 and make it ${counter + 1}`
</button>
</div>)
}
//All elements depending on counter will update when
counter changes value
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Virtual DOM
In JavaScript one of the most performance degrading actions is updating
the DOM, that is the elements that compose your webpage. As such, wouldn’t
be great if we updated the DOM as less as possible? Enter the Virtual DOM.
With React we have two versions of the DOM: the one that’s being displayed
in the browser and an internal DOM that reflects the processed output by
React. By comparing both DOMs we can update only the elements that we
need. Without some technique like Virtual DOM we may need to update all
the elements even if we modified only one, incurring a performance hit.
3
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Modular Structure
In React, each part of the UI can be divided in smaller components. This
makes coding more manageable and easier to work in a team, it allows the
production of self-contained components that can be reused easily and since
it’s JavaScript it allows data passing between components: no more storing
data in the DOM and in humongous global states.
4
An Introduction To React For Frontend Developers hi@nakamurasei.com
Why React?
Modular Structure
Let’s see how components can make our code more manageable.
4
Vanilla JS React JS
let fruits = [“mango”, “apple”, “banana”, “orange”];
const div = document.createElement(“div”);
//Create <div>
body.appendChild(div); //Append to body
function addFruits() {
fruits.forEach(fruit => {
const p = document.createElement(“p”);
p.innerText = fruit;
div.appendChild(p);})
}
addFruits();
import React, {useState, useEffect} from “react”;
import Fruits from “./Fruits.js”;
export default function App() {
const [fruits, setFruits] = useState([“mango”,
“apple”, “banana”, “orange”]);
return (<Fruits fruits={fruits}/>);
}
import React, {useState, useEffect} from “react”;
export default function Fruits(props) {
return (<div>{props.fruits.map(fruit=><p
key={fruit}>{fruit}</p>)}</div>);
}
//”fruits” was received from App() via props
App.js
Fruits.js
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
You can build a React application with either classes or functions. While
classes are useful when building complex components, in most cases using
functions will be more readable and concise.
You can build functional components in these ways. Note that we are
exporting the function, so we can use it in another place.
import React from “react”;
export default function App() {
return(<p>Hello World</p>);
}
import React from “react”;
const App = () => {
return(<p>Hello World</p>);
}
export default App;
An Introduction To React For Frontend Developers hi@nakamurasei.com
What you are seeing in orange isn’t HTML, is something called JSX, an
extension of JavaScript used in React. When you are using JSX you are
actually calling a function named “createElement” which outputs the HTML
you are expecting.
React Basics
JSX
import React from “react”;
export default function App() {
return(<p>Hello World</p>);
}
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX
JSX elements must be closed at all times. While most HTML elements follow
the <></> structure, some elements don’t have an end tag (like <input> or
<img>). In those cases you must add a / right before >, effectively closing it.
<input type=”submit”> <input type=”submit”/>
HTML React’s JSX
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX
As we are seeing, JSX isn’t an exact copy of HTML. If you want to style your
components using CSS, the “class” property isn’t allowed. Instead, use
“className”.
<p class=”hello”>Hello</p> <p className=”hello”>Hello</p>
HTML React’s JSX
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX
One of the advantages of JSX is that we can use JavaScript code instead of
strings. To do so we wrap our code in {}. This allows us to use variables,
render CSS class names conditionally, call functions and more.
<p className=”hello”>{message}</p>
//<p>’s content is the variable “message”.
React’s JSX
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
The code inside {} must always return something (even null).
We can’t add more than one line (as in separate instructions divided by ;),
however functions can have multiples lines inside it.
<p className=”hello”>{
function renderStuff () {
return “Hello”
};
renderStuff()}
</p>
<p className=”hello”>{
“Hello”
}</p>
Invalid: Separate instructions OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
We can’t use if as it doesn’t always return something. We can use a ternary
expression instead, where the else clause returns null.
<p className=”hello”>{
if(name === “Kentaro”){
return “You are
Kentaro”}
}</p>
<p className=”hello”>{
name === “Kentaro” ? “You are
Kentaro” : null
}</p>
Invalid: if OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
To replace an if else clause use the ternary expression in the same way.
<p className=”hello”>{
if(name === “Kentaro”){
return “You are
Kentaro”} else {
return “You are not Kentaro”
}
}</p>
<p className=”hello”>{
name === “Kentaro” ? “You are
Kentaro” : “You are not Kentaro”
}</p>
Invalid: if OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
JSX - Using JS Code inside {}
We can’t add loops (such as for or forEach). However we can use array’s map,
since it will always return an array.
<div>{
names.forEach(name => <p
key={name}>{name}</p>)}
</div>
<div>{
names.map(name => <p
key={name}>{name}</p>)
}</div>
Invalid: forEach
<div>{
for(i = 0, n=names.length; i<n; i++){
return <p key={names[i]}>names[i]</p>}
}</div>
Invalid: for
OK
An Introduction To React For Frontend Developers hi@nakamurasei.com
import React from “react”;
import MyFunction from “./MyFunction.js”;
const App = () => {
return <MyFunction name=”Kentaro”/>;
}
export default App;
App.js
import React from “react”;
const MyFunction = (props) => {
return <p>{props.name}</p>;
}
export default MyFunction;
MyFunction.js
React Basics
Modularity
By splitting your application in several files code reuse and teamwork become
easier. To import a component use “import” at the top of your file.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
Using state inside components
To store information inside our components we can use “useState”, a React
Hook (function that enables access to the state and lifecycle features of
React.)
import React, {useState} from “react”; import React, {useState} from “react”;
export default function App() {
const [counter, setCounter] =
useState(0);
return <p>{counter}</p>;
}
1: Import useState at the top 2. Call useState inside the function
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
Anatomy of useState
const [counter, setCounter] = useState(0);
1: Pick a name for the
variable that will hold the
state’s value.
2: This is the function that will
set the state’s value.
By convention name it “set” +
the name picked in 1
(camelCase).
3: This is the initial value of
the state. Ideally set it to the
same type as the expected
value. For example, if you are
expecting a number you can
set it to 0.
Functions, variables, even null
and undefined is OK.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useState example
import React, {useState} from “react”;
export default function App() {
const [counter, setCounter] =
useState(0);
return (<div>
<p>{counter}</p>
<button onClick={() =>
setCounter(counter + 1)}>+1</button>
</div>
)
}
1: <p/> will hold the counter value. At
initialization its value will be 0, as defined in
useState.
2: When <button/> is clicked, the counter’s
value will be incremented by 1. Automatically,
every place that holds “counter” will update its
value.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useEffect
Another React Hook is “useEffect”. Whatever instructions are inside of
useEffect will get executed whenever there’s an update to its dependences.
This lets us fetch data at component mount, execute functions when new
information is received and more.
import React, {useEffect} from “react”; import React, {useEffect} from “react”;
export default function App() {
useEffect(() => {
//Place code here
}, []);
return <p>Hello world</p>;
}
1: Import useEffect at the top 2. Call useEffect inside the function
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useEffect’s Behaviour
The behaviour of useEffect changes depending on the dependencies defined
in the [] at the end.
useEffect(() => {
//Place code here
}, []);
Component mount
If nothing is defined inside [], the code inside
useEffect will execute only once at
component mount. This replaces React’s
lifecycle method componentDidMount.
useEffect(() => {
//Place code here
}, [varName]);
Update at dependency change
The code will execute once at component
mount and everytime there’s a change of the
dependencies defined inside []. You can add as
many dependencies you wish.
An Introduction To React For Frontend Developers hi@nakamurasei.com
React Basics
useEffect example
import React, {useState, useEffect} from
“react”;
export default function App() {
const [counter, setCounter] =
useState(0);
useEffect(()=>{
console.log(`Counter value is
${counter}`);
}, [counter]);
return (<div>
<p>{counter}</p>
<button onClick={() =>
setCounter(counter + 1)}>+1</button>
</div>
)
}
Because “counter” is defined as a dependency
of useEffect, it will console.log every time
“counter” is incremented.
Sergio Nakamura | nakamurasei.com hi@nakamurasei.com
Thank you!

More Related Content

What's hot (20)

PPT
Angular 8
Sunil OS
 
PDF
Vaadin & Web Components
Joonas Lehtinen
 
PDF
Vaadin Introduction, 7.3 edition
Joonas Lehtinen
 
PDF
Beginning AngularJS
Troy Miles
 
PPTX
Intoduction to Angularjs
Gaurav Agrawal
 
PDF
Adding User Management to Node.js
Dev_Events
 
PDF
Part 1 implementing a simple_web_service
krishmdkk
 
PDF
Web Components for Java Developers
Joonas Lehtinen
 
PDF
Flutter State Management Using GetX.pdf
Katy Slemon
 
PDF
Introduction to Vaadin
netomi
 
PPT
GWT Training - Session 1/3
Faiz Bashir
 
PDF
Workshop: Building Vaadin add-ons
Sami Ekblad
 
PDF
JOSA TechTalks - Better Web Apps with React and Redux
Jordan Open Source Association
 
PDF
React Js Simplified
Sunil Yadav
 
PDF
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
PDF
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
PDF
Angular JS2 Training Session #2
Paras Mendiratta
 
PDF
Hackathon - Building vaadin add on components
Joonas Lehtinen
 
PDF
An introduction to AngularJS
Yogesh singh
 
PDF
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Luciano Mammino
 
Angular 8
Sunil OS
 
Vaadin & Web Components
Joonas Lehtinen
 
Vaadin Introduction, 7.3 edition
Joonas Lehtinen
 
Beginning AngularJS
Troy Miles
 
Intoduction to Angularjs
Gaurav Agrawal
 
Adding User Management to Node.js
Dev_Events
 
Part 1 implementing a simple_web_service
krishmdkk
 
Web Components for Java Developers
Joonas Lehtinen
 
Flutter State Management Using GetX.pdf
Katy Slemon
 
Introduction to Vaadin
netomi
 
GWT Training - Session 1/3
Faiz Bashir
 
Workshop: Building Vaadin add-ons
Sami Ekblad
 
JOSA TechTalks - Better Web Apps with React and Redux
Jordan Open Source Association
 
React Js Simplified
Sunil Yadav
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
Angular JS2 Training Session #2
Paras Mendiratta
 
Hackathon - Building vaadin add on components
Joonas Lehtinen
 
An introduction to AngularJS
Yogesh singh
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Luciano Mammino
 

Similar to Introduction to React for Frontend Developers (20)

PDF
React: JSX and Top Level API
Fabio Biondi
 
PDF
Server side rendering with React and Symfony
Ignacio Martín
 
PPTX
React & Redux for noobs
[T]echdencias
 
PPTX
React JS: A Secret Preview
valuebound
 
PDF
Fundamental concepts of react js
StephieJohn
 
PPTX
Ways to Set Focus on an Input Field After Rendering in React.pptx
BOSC Tech Labs
 
PPTX
ReactJS.pptx
SamyakShetty2
 
PDF
Tech Talk on ReactJS
Atlogys Technical Consulting
 
PPTX
React outbox
Angela Lehru
 
PPTX
Build web apps with react js
dhanushkacnd
 
PDF
Lessons from a year of building apps with React Native
Ryan Boland
 
PDF
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
PPTX
How to create components in react js
BOSC Tech Labs
 
PPTX
React Basic and Advance || React Basic
rafaqathussainc077
 
PDF
A full introductory guide to React
Jean Carlo Emer
 
PDF
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
PDF
React JS Interview Questions PDF By ScholarHat
Scholarhat
 
PPTX
Building user interface with react
Amit Thakkar
 
PDF
React Native +Redux + ES6 (Updated)
Chiew Carol
 
React: JSX and Top Level API
Fabio Biondi
 
Server side rendering with React and Symfony
Ignacio Martín
 
React & Redux for noobs
[T]echdencias
 
React JS: A Secret Preview
valuebound
 
Fundamental concepts of react js
StephieJohn
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
BOSC Tech Labs
 
ReactJS.pptx
SamyakShetty2
 
Tech Talk on ReactJS
Atlogys Technical Consulting
 
React outbox
Angela Lehru
 
Build web apps with react js
dhanushkacnd
 
Lessons from a year of building apps with React Native
Ryan Boland
 
Full Stack React Workshop [CSSC x GDSC]
GDSC UofT Mississauga
 
How to create components in react js
BOSC Tech Labs
 
React Basic and Advance || React Basic
rafaqathussainc077
 
A full introductory guide to React
Jean Carlo Emer
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
React JS Interview Questions PDF By ScholarHat
Scholarhat
 
Building user interface with react
Amit Thakkar
 
React Native +Redux + ES6 (Updated)
Chiew Carol
 
Ad

Recently uploaded (20)

PDF
BroadLink Cloud Service introduction.pdf
DevendraDwivdi1
 
PPTX
Q1 English3 Week5 [email protected]
JenniferCawaling1
 
PPTX
BitRecover OST to PST Converter Software
antoniogosling01
 
PPT
Almos Entirely Correct Mixing with Apps to Voting
gapati2964
 
PDF
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
PDF
Materi tentang From Digital Economy to Fintech.pdf
Abdul Hakim
 
PDF
The Convergence of Threat Behaviors Across Intrusions
Joe Slowik
 
PPTX
Class_4_Limbgvchgchgchgchgchgcjhgchgcnked_Lists.pptx
test123n
 
PPTX
The ARUBA Kind of new Proposal Umum .pptx
andiwarneri
 
PDF
I Want to join occult brotherhood for money ritual#((+2347089754903))
haragonoccult
 
PPTX
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
Taqyea
 
PDF
Transmission Control Protocol (TCP) and Starlink
APNIC
 
PDF
03 Internal Analysis Strategik Manajemen.pdf
AhmadRifaldhi
 
PPTX
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
taqyed
 
PPTX
Lesson 1.1 Career-Opportunities-in-Ict.pptx
lizelgumadlas1
 
PDF
Clive Dickens RedTech Public Copy - Collaborate or Die
Clive Dickens
 
PPTX
My Mother At 66! (2).pptx00000000000000000000000000000
vedapattisiddharth
 
PDF
Beginning-Laravel-Build-Websites-with-Laravel-5.8-by-Sanjib-Sinha-z-lib.org.pdf
TagumLibuganonRiverB
 
PDF
web application development company in bangalore.pdf
https://dkpractice.co.in/seo.html tech
 
PDF
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
Mostofa Kamal Al-Azad
 
BroadLink Cloud Service introduction.pdf
DevendraDwivdi1
 
BitRecover OST to PST Converter Software
antoniogosling01
 
Almos Entirely Correct Mixing with Apps to Voting
gapati2964
 
Slides: Eco Economic Epochs for The World Game (s) pdf
Steven McGee
 
Materi tentang From Digital Economy to Fintech.pdf
Abdul Hakim
 
The Convergence of Threat Behaviors Across Intrusions
Joe Slowik
 
Class_4_Limbgvchgchgchgchgchgcjhgchgcnked_Lists.pptx
test123n
 
The ARUBA Kind of new Proposal Umum .pptx
andiwarneri
 
I Want to join occult brotherhood for money ritual#((+2347089754903))
haragonoccult
 
原版一样(ANU毕业证书)澳洲澳大利亚国立大学毕业证在线购买
Taqyea
 
Transmission Control Protocol (TCP) and Starlink
APNIC
 
03 Internal Analysis Strategik Manajemen.pdf
AhmadRifaldhi
 
原版一样(ISM毕业证书)德国多特蒙德国际管理学院毕业证多少钱
taqyed
 
Lesson 1.1 Career-Opportunities-in-Ict.pptx
lizelgumadlas1
 
Clive Dickens RedTech Public Copy - Collaborate or Die
Clive Dickens
 
My Mother At 66! (2).pptx00000000000000000000000000000
vedapattisiddharth
 
Beginning-Laravel-Build-Websites-with-Laravel-5.8-by-Sanjib-Sinha-z-lib.org.pdf
TagumLibuganonRiverB
 
web application development company in bangalore.pdf
https://dkpractice.co.in/seo.html tech
 
B M Mostofa Kamal Al-Azad [Document & Localization Expert]
Mostofa Kamal Al-Azad
 
Ad

Introduction to React for Frontend Developers

  • 1. Sergio Nakamura | nakamurasei.com [email protected] An Introduction To React For Frontend Developers
  • 2. An Introduction To React For Frontend Developers [email protected] Disclaimer Many of the techniques displayed aren’t exclusive to React. In fact, React is built in JavaScript and as such all React features can be implemented in JavaScript (and have existed for years, albeit with less flashy names). However React offers a “framework”, a structure you can use to build your applications. While not many people will implement a pub-sub method or a helper method to simplify element creation, many people will use a framework. You can use its features without knowing its inner workings, without reinventing the wheel, and using the same conventions.
  • 3. An Introduction To React For Frontend Developers [email protected] Why React? JavaScript has been used for over two decades to add interactivity to webpages: adding, removing or modifying elements, responding to user input and sending and receiving data from external sources. React (just like Angular, Vue and many more) are frameworks built on JavaScript that allow easier development of user interfaces. 1. Declarative Style 2. Automatic Updates 3. Virtual DOM 4. Modular Structure
  • 4. An Introduction To React For Frontend Developers [email protected] Why React? Declarative Style If you’ve previously used JavaScript you may have found yourself telling the browser each step to make: select X element, set the content to Y, do Z when clicked... Having to tell each step can be classified as an “Imperative” style: forgetting a step may lead to errors, because the browser just follows instructions, it doesn’t know what you’re actually looking for. In React, you are following most of the time a “Declarative” style, you tell what you want and provide the data. React does the work behind the scenes to translate that information to the instructions your browser understands. 1
  • 5. An Introduction To React For Frontend Developers [email protected] Why React? Declarative Style Let’s render a <button> and console.log when clicked, in Vanilla JS and React. Vanilla JS React JS 1 const btn = document.createElement(“button”); //Create <button> body.appendChild(btn); //Append to body btn.innerText = “Click me”; //Change text btn.addEventListener(“click”, () => { console.log(“Clicked”); }); //Log “Clicked” when clicked import React from “react”; export default function App() { return ( <button onClick={() => console.log(“Clicked”)}> Click me </button> ); } //I want a <button> with “Click me” as text that logs “Clicked” when clicked
  • 6. An Introduction To React For Frontend Developers [email protected] Why React? Automatic Updates As your application grows adding an element and setting a value isn’t enough: you may need to update its content as you receive new information. Without a framework as React, you may have to tell the browser to update the elements every time we receive new information. While this doesn’t seem a big deal at first it can get ugly fast. Using React, all the elements depending on a piece of data get updated automatically when the data changes. 2
  • 7. An Introduction To React For Frontend Developers [email protected] Why React? Automatic Updates Let’s see a simple button that +1 to a counter. The counter variable is seen in two places at the time. 2 Vanilla JS React JS let counter = 0; //Counter const p = document.createElement(“p”); //Create a <p> p.innerText = counter; //Set <p>’s text body.appendChild(p); //Append <p> to the body const btn = document.createElement(“button”); //Create a <button> btn.innerText = `+1 and make it ${counter + 1}`; //Set <button>’s text body.appendChild(btn); //Append <button> to the body btn.addEventListener(“click”, () => { counter = counter ++; //Update the counter p.innerText = counter; //Update <p> btn.innerText = `+1 and make it ${counter + 1}`; // Update <btn> }) import React, {useState} from “react”; export default function App() { const [counter, setCounter] = useState(0); return (<div> <p>{counter}</p> <button onClick={() => setCounter(counter++)}> `+1 and make it ${counter + 1}` </button> </div>) } //All elements depending on counter will update when counter changes value
  • 8. An Introduction To React For Frontend Developers [email protected] Why React? Virtual DOM In JavaScript one of the most performance degrading actions is updating the DOM, that is the elements that compose your webpage. As such, wouldn’t be great if we updated the DOM as less as possible? Enter the Virtual DOM. With React we have two versions of the DOM: the one that’s being displayed in the browser and an internal DOM that reflects the processed output by React. By comparing both DOMs we can update only the elements that we need. Without some technique like Virtual DOM we may need to update all the elements even if we modified only one, incurring a performance hit. 3
  • 9. An Introduction To React For Frontend Developers [email protected] Why React? Modular Structure In React, each part of the UI can be divided in smaller components. This makes coding more manageable and easier to work in a team, it allows the production of self-contained components that can be reused easily and since it’s JavaScript it allows data passing between components: no more storing data in the DOM and in humongous global states. 4
  • 10. An Introduction To React For Frontend Developers [email protected] Why React? Modular Structure Let’s see how components can make our code more manageable. 4 Vanilla JS React JS let fruits = [“mango”, “apple”, “banana”, “orange”]; const div = document.createElement(“div”); //Create <div> body.appendChild(div); //Append to body function addFruits() { fruits.forEach(fruit => { const p = document.createElement(“p”); p.innerText = fruit; div.appendChild(p);}) } addFruits(); import React, {useState, useEffect} from “react”; import Fruits from “./Fruits.js”; export default function App() { const [fruits, setFruits] = useState([“mango”, “apple”, “banana”, “orange”]); return (<Fruits fruits={fruits}/>); } import React, {useState, useEffect} from “react”; export default function Fruits(props) { return (<div>{props.fruits.map(fruit=><p key={fruit}>{fruit}</p>)}</div>); } //”fruits” was received from App() via props App.js Fruits.js
  • 11. An Introduction To React For Frontend Developers [email protected] React Basics You can build a React application with either classes or functions. While classes are useful when building complex components, in most cases using functions will be more readable and concise. You can build functional components in these ways. Note that we are exporting the function, so we can use it in another place. import React from “react”; export default function App() { return(<p>Hello World</p>); } import React from “react”; const App = () => { return(<p>Hello World</p>); } export default App;
  • 12. An Introduction To React For Frontend Developers [email protected] What you are seeing in orange isn’t HTML, is something called JSX, an extension of JavaScript used in React. When you are using JSX you are actually calling a function named “createElement” which outputs the HTML you are expecting. React Basics JSX import React from “react”; export default function App() { return(<p>Hello World</p>); }
  • 13. An Introduction To React For Frontend Developers [email protected] React Basics JSX JSX elements must be closed at all times. While most HTML elements follow the <></> structure, some elements don’t have an end tag (like <input> or <img>). In those cases you must add a / right before >, effectively closing it. <input type=”submit”> <input type=”submit”/> HTML React’s JSX
  • 14. An Introduction To React For Frontend Developers [email protected] React Basics JSX As we are seeing, JSX isn’t an exact copy of HTML. If you want to style your components using CSS, the “class” property isn’t allowed. Instead, use “className”. <p class=”hello”>Hello</p> <p className=”hello”>Hello</p> HTML React’s JSX
  • 15. An Introduction To React For Frontend Developers [email protected] React Basics JSX One of the advantages of JSX is that we can use JavaScript code instead of strings. To do so we wrap our code in {}. This allows us to use variables, render CSS class names conditionally, call functions and more. <p className=”hello”>{message}</p> //<p>’s content is the variable “message”. React’s JSX
  • 16. An Introduction To React For Frontend Developers [email protected] React Basics JSX - Using JS Code inside {} The code inside {} must always return something (even null). We can’t add more than one line (as in separate instructions divided by ;), however functions can have multiples lines inside it. <p className=”hello”>{ function renderStuff () { return “Hello” }; renderStuff()} </p> <p className=”hello”>{ “Hello” }</p> Invalid: Separate instructions OK
  • 17. An Introduction To React For Frontend Developers [email protected] React Basics JSX - Using JS Code inside {} We can’t use if as it doesn’t always return something. We can use a ternary expression instead, where the else clause returns null. <p className=”hello”>{ if(name === “Kentaro”){ return “You are Kentaro”} }</p> <p className=”hello”>{ name === “Kentaro” ? “You are Kentaro” : null }</p> Invalid: if OK
  • 18. An Introduction To React For Frontend Developers [email protected] React Basics JSX - Using JS Code inside {} To replace an if else clause use the ternary expression in the same way. <p className=”hello”>{ if(name === “Kentaro”){ return “You are Kentaro”} else { return “You are not Kentaro” } }</p> <p className=”hello”>{ name === “Kentaro” ? “You are Kentaro” : “You are not Kentaro” }</p> Invalid: if OK
  • 19. An Introduction To React For Frontend Developers [email protected] React Basics JSX - Using JS Code inside {} We can’t add loops (such as for or forEach). However we can use array’s map, since it will always return an array. <div>{ names.forEach(name => <p key={name}>{name}</p>)} </div> <div>{ names.map(name => <p key={name}>{name}</p>) }</div> Invalid: forEach <div>{ for(i = 0, n=names.length; i<n; i++){ return <p key={names[i]}>names[i]</p>} }</div> Invalid: for OK
  • 20. An Introduction To React For Frontend Developers [email protected] import React from “react”; import MyFunction from “./MyFunction.js”; const App = () => { return <MyFunction name=”Kentaro”/>; } export default App; App.js import React from “react”; const MyFunction = (props) => { return <p>{props.name}</p>; } export default MyFunction; MyFunction.js React Basics Modularity By splitting your application in several files code reuse and teamwork become easier. To import a component use “import” at the top of your file.
  • 21. An Introduction To React For Frontend Developers [email protected] React Basics Using state inside components To store information inside our components we can use “useState”, a React Hook (function that enables access to the state and lifecycle features of React.) import React, {useState} from “react”; import React, {useState} from “react”; export default function App() { const [counter, setCounter] = useState(0); return <p>{counter}</p>; } 1: Import useState at the top 2. Call useState inside the function
  • 22. An Introduction To React For Frontend Developers [email protected] React Basics Anatomy of useState const [counter, setCounter] = useState(0); 1: Pick a name for the variable that will hold the state’s value. 2: This is the function that will set the state’s value. By convention name it “set” + the name picked in 1 (camelCase). 3: This is the initial value of the state. Ideally set it to the same type as the expected value. For example, if you are expecting a number you can set it to 0. Functions, variables, even null and undefined is OK.
  • 23. An Introduction To React For Frontend Developers [email protected] React Basics useState example import React, {useState} from “react”; export default function App() { const [counter, setCounter] = useState(0); return (<div> <p>{counter}</p> <button onClick={() => setCounter(counter + 1)}>+1</button> </div> ) } 1: <p/> will hold the counter value. At initialization its value will be 0, as defined in useState. 2: When <button/> is clicked, the counter’s value will be incremented by 1. Automatically, every place that holds “counter” will update its value.
  • 24. An Introduction To React For Frontend Developers [email protected] React Basics useEffect Another React Hook is “useEffect”. Whatever instructions are inside of useEffect will get executed whenever there’s an update to its dependences. This lets us fetch data at component mount, execute functions when new information is received and more. import React, {useEffect} from “react”; import React, {useEffect} from “react”; export default function App() { useEffect(() => { //Place code here }, []); return <p>Hello world</p>; } 1: Import useEffect at the top 2. Call useEffect inside the function
  • 25. An Introduction To React For Frontend Developers [email protected] React Basics useEffect’s Behaviour The behaviour of useEffect changes depending on the dependencies defined in the [] at the end. useEffect(() => { //Place code here }, []); Component mount If nothing is defined inside [], the code inside useEffect will execute only once at component mount. This replaces React’s lifecycle method componentDidMount. useEffect(() => { //Place code here }, [varName]); Update at dependency change The code will execute once at component mount and everytime there’s a change of the dependencies defined inside []. You can add as many dependencies you wish.
  • 26. An Introduction To React For Frontend Developers [email protected] React Basics useEffect example import React, {useState, useEffect} from “react”; export default function App() { const [counter, setCounter] = useState(0); useEffect(()=>{ console.log(`Counter value is ${counter}`); }, [counter]); return (<div> <p>{counter}</p> <button onClick={() => setCounter(counter + 1)}>+1</button> </div> ) } Because “counter” is defined as a dependency of useEffect, it will console.log every time “counter” is incremented.
  • 27. Sergio Nakamura | nakamurasei.com [email protected] Thank you!