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

PPTX
Dsc Charusat Learning React Part 1
PDF
Vaadin Components
PPTX
React js programming concept
PPTX
React render props
PDF
Vaadin Components @ Angular U
PDF
A gently introduction to AngularJS
PPTX
React 101 by Anatoliy Sieryi
PDF
AngularJS Project Setup step-by- step guide - RapidValue Solutions
Dsc Charusat Learning React Part 1
Vaadin Components
React js programming concept
React render props
Vaadin Components @ Angular U
A gently introduction to AngularJS
React 101 by Anatoliy Sieryi
AngularJS Project Setup step-by- step guide - RapidValue Solutions

What's hot (20)

PPT
Angular 8
PDF
Vaadin & Web Components
PDF
Vaadin Introduction, 7.3 edition
PDF
Beginning AngularJS
PPTX
Intoduction to Angularjs
PDF
Adding User Management to Node.js
PDF
Part 1 implementing a simple_web_service
PDF
Web Components for Java Developers
PDF
Flutter State Management Using GetX.pdf
PDF
Introduction to Vaadin
PPT
GWT Training - Session 1/3
PDF
Workshop: Building Vaadin add-ons
PDF
JOSA TechTalks - Better Web Apps with React and Redux
PDF
React Js Simplified
PDF
Angular 7 Firebase5 CRUD Operations with Reactive Forms
PDF
JSLab. Алексей Волков. "React на практике"
PDF
Angular JS2 Training Session #2
PDF
Hackathon - Building vaadin add on components
PDF
An introduction to AngularJS
PDF
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Angular 8
Vaadin & Web Components
Vaadin Introduction, 7.3 edition
Beginning AngularJS
Intoduction to Angularjs
Adding User Management to Node.js
Part 1 implementing a simple_web_service
Web Components for Java Developers
Flutter State Management Using GetX.pdf
Introduction to Vaadin
GWT Training - Session 1/3
Workshop: Building Vaadin add-ons
JOSA TechTalks - Better Web Apps with React and Redux
React Js Simplified
Angular 7 Firebase5 CRUD Operations with Reactive Forms
JSLab. Алексей Волков. "React на практике"
Angular JS2 Training Session #2
Hackathon - Building vaadin add on components
An introduction to AngularJS
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Ad

Similar to Introduction to React for Frontend Developers (20)

PDF
React: JSX and Top Level API
PDF
Server side rendering with React and Symfony
PPTX
React & Redux for noobs
PPTX
React JS: A Secret Preview
PDF
Fundamental concepts of react js
PPTX
Ways to Set Focus on an Input Field After Rendering in React.pptx
PPTX
ReactJS.pptx
PDF
Tech Talk on ReactJS
PPTX
React outbox
PPTX
Build web apps with react js
PDF
Lessons from a year of building apps with React Native
PDF
Full Stack React Workshop [CSSC x GDSC]
PPTX
How to create components in react js
PPTX
React Basic and Advance || React Basic
PDF
A full introductory guide to React
PDF
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
PDF
React JS Interview Questions PDF By ScholarHat
PPTX
Building user interface with react
PDF
React Native +Redux + ES6 (Updated)
React: JSX and Top Level API
Server side rendering with React and Symfony
React & Redux for noobs
React JS: A Secret Preview
Fundamental concepts of react js
Ways to Set Focus on an Input Field After Rendering in React.pptx
ReactJS.pptx
Tech Talk on ReactJS
React outbox
Build web apps with react js
Lessons from a year of building apps with React Native
Full Stack React Workshop [CSSC x GDSC]
How to create components in react js
React Basic and Advance || React Basic
A full introductory guide to React
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
React JS Interview Questions PDF By ScholarHat
Building user interface with react
React Native +Redux + ES6 (Updated)
Ad

Recently uploaded (20)

PDF
simpleintnettestmetiaerl for the simple testint
PDF
Virtual Guard Technology Provider_ Remote Security Service Solutions.pdf
PDF
The Ikigai Template _ Recalibrate How You Spend Your Time.pdf
PPTX
1402_iCSC_-_RESTful_Web_APIs_--_Josef_Hammer.pptx
PDF
Lean-Manufacturing-Tools-Techniques-and-How-To-Use-Them.pdf
PPTX
COPD_Management_Exacerbation_Detailed_Placeholders.pptx
DOCX
Powerful Ways AIRCONNECT INFOSYSTEMS Pvt Ltd Enhances IT Infrastructure in In...
PDF
Top 8 Trusted Sources to Buy Verified Cash App Accounts.pdf
PDF
Exploring The Internet Of Things(IOT).ppt
PPTX
Reading as a good Form of Recreation
PPTX
在线订购名古屋艺术大学毕业证, buy NUA diploma学历认证失败怎么办
PPTX
IPCNA VIRTUAL CLASSES INTERMEDIATE 6 PROJECT.pptx
PDF
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
PDF
Understand the Gitlab_presentation_task.pdf
PDF
Course Overview and Agenda cloud security
PDF
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
PPTX
Viva Digitally Software-Defined Wide Area Network.pptx
DOCX
Memecoinist Update: Best Meme Coins 2025, Trump Meme Coin Predictions, and th...
PPTX
Layers_of_the_Earth_Grade7.pptx class by
PDF
BIOCHEM CH2 OVERVIEW OF MICROBIOLOGY.pdf
simpleintnettestmetiaerl for the simple testint
Virtual Guard Technology Provider_ Remote Security Service Solutions.pdf
The Ikigai Template _ Recalibrate How You Spend Your Time.pdf
1402_iCSC_-_RESTful_Web_APIs_--_Josef_Hammer.pptx
Lean-Manufacturing-Tools-Techniques-and-How-To-Use-Them.pdf
COPD_Management_Exacerbation_Detailed_Placeholders.pptx
Powerful Ways AIRCONNECT INFOSYSTEMS Pvt Ltd Enhances IT Infrastructure in In...
Top 8 Trusted Sources to Buy Verified Cash App Accounts.pdf
Exploring The Internet Of Things(IOT).ppt
Reading as a good Form of Recreation
在线订购名古屋艺术大学毕业证, buy NUA diploma学历认证失败怎么办
IPCNA VIRTUAL CLASSES INTERMEDIATE 6 PROJECT.pptx
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
Understand the Gitlab_presentation_task.pdf
Course Overview and Agenda cloud security
📍 LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1 TERPOPULER DI INDONESIA ! 🌟
Viva Digitally Software-Defined Wide Area Network.pptx
Memecoinist Update: Best Meme Coins 2025, Trump Meme Coin Predictions, and th...
Layers_of_the_Earth_Grade7.pptx class by
BIOCHEM CH2 OVERVIEW OF MICROBIOLOGY.pdf

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!