SlideShare a Scribd company logo
Rome 24-25 MARCH 2017
{ Universal JS Web Applications with React
Luciano Mammino
loige.link/codemotion-rome-2017
1
WHO IS
LUCIANO
lmammino
loige
loige.co
2
-20% eBook
NJDPEB20
-15% Print
NJDPPB15
loige.link/node-book
3
fullstackbulletin.com 4
AGENDA
1. The term "Universal" JS
2. Who & Why
3. Common problems and technologies
4. Building a frontend only Single Page App
5. Making it universal
5
ISOMORPHIC
loige.link/universal-js-story
UNIVERSAL WHAT?
6
NOT ONLY
FOR THE WEB...
Desktop applications
Mobile applications
Hardware!
7
ADVANTAGES
OF UNIVERSAL JAVASCRIPT
"JavaScript-only" development
Maintainability
Better SEO
Faster "perceived" load time
8
ADVANTAGES...
MORE
Keep using React/JS paradigms also to
generate "static" websites
Speed up content loading with
linkprefetch
loige.link/universal-react-made-easy-talk
9
IN THE WILD
10
IT LOOKS GREAT BUT...
11
MODULE SHARING
Use Node.js modules in the browser
UMD
12
UNIVERSAL RENDERING
Render the views of the application from
the server (first request) and then in the
browser (next requests)
13
UNIVERSAL ROUTING
Recognise the view associated to the
current route from both the server and the
browser.
14
UNIVERSAL DATA RETRIEVAL
Access data (and APIs) from both the server
and the browser.
AXIOS UNIVERSAL
FETCH
15
UNIVERSAL STATE
MANAGEMENT
Manage changes on the state tree both on
the server and the client...
16
FUTURISTIC/ALTERNATIVE JS?!
17
18
OK...
LET'S STOP COMPLAINING
AND BUILD SOMETHING!
19
WHAT ARE WE
GOING TO BUILD?
loige.link/judo-heroes-app​
loige.link/judo-heroes-tutorial
v 2.0
20
21
22
23
curl -sS "https://judo-heroes.herokuapp.com/athlete/teddy-riner"
24
WHAT TOOLS ARE
WE GOING TO USE?
v2 v15.4
v4
v5-alpha
25
Dependencies 😺😺
yarn add 
babel-cli@6.18.0 
babel-core@6.18.2 
babel-preset-es2015@6.18.0 
babel-preset-react@6.16.0 
ejs@2.5.2 
express@5.0.0-alpha.5 
react@15.4.2 
react-dom@15.4.2 
react-router-dom@4.0.0 
webpack@2.2.1
26
27
The data set
// src/data/athletes.js
const athletes = [
{
id: 'driulis-gonzalez',
name: 'Driulis González',
country: {
id: 'cu',
name: 'Cuba',
icon: 'flag-cu.png',
},
birth: '1973',
image: 'driulis-gonzalez.jpg',
cover: 'driulis-gonzalez-cover.jpg',
link: 'https://en.wikipedia.org/wiki/Driulis_González',
medals: [
{ id: 1, year: '1992', type: 'B', city: 'Barcelona', event: 'Olympic Games', category
{ id: 2, year: '1993', type: 'B', city: 'Hamilton', event: 'World Championships', cat
{ id: 3, year: '1995', type: 'G', city: 'Chiba', event: 'World Championships', catego
{ id: 4, year: '1995', type: 'G', city: 'Mar del Plata', event: 'Pan American Games',
{ id: 5, year: '1996', type: 'G', city: 'Atlanta', event: 'Olympic Games', category:
// ...
],
},
// ...
];
export default athletes;
28
REACT
COMPONENTS
29
Layout component
30
IndexPage component
31
AthletePage component
32
NotFoundPage component
33
AthletePreview component
34
AthletesMenu component
35
Flag component
36
Medal component
37
// src/components/Layout.js
import React from 'react';
import { Link } from 'react-router-dom';
export const Layout = props => (
<div className="app-container">
<header>
<Link to="/">
<img className="logo" src="/img/logo-judo-heroes.png" />
</Link>
</header>
<div className="app-content">{props.children}</div>
<footer>
<p>
This is a demo app to showcase
<strong>universal Javascript</strong>
with <strong>React</strong> and
<strong>Express</strong>.
</p>
</footer>
</div>
);
export default Layout;
38
// src/components/IndexPage.js
import React from 'react';
import { AthletePreview } from './AthletePreview';
export const IndexPage = ({ athletes }) => (
<div className="home">
<div className="athletes-selector">
{
athletes.map( athleteData =>
<AthletePreview
key={athleteData.id}
{...athleteData} />
)
}
</div>
</div>
);
export default IndexPage;
39
// src/components/AthletePreview.js
import React from 'react';
import { Link } from 'react-router';
export const AthletePreview = (props) => (
<Link to={`/athlete/${props.id}`}>
<div className="athlete-preview">
<img src={`img/${props.image}`}/>
<h2 className="name">{props.name}</h2>
<span className="medals-count">
<img src="/img/medal.png"/> {props.medals.length}
</span>
</div>
</Link>
);
export default AthletePreview;
40
ROUTING
41
2 ROUTES
Index Page: /
Athlete Page: /athlete/:id
42
// src/components/App.js
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import { Layout } from './Layout';
import { IndexPage } from './IndexPage';
import { AthletePage } from './AthletePage';
import { NotFoundPage } from './NotFoundPage';
import athletes from '../data/athletes';
// ...
export const App = () => (
<Layout>
<Switch>
<Route exact path="/" render={renderIndex} />
<Route exact path="/athlete/:id" render={renderAthlete} />
<Route component={NotFoundPage} />
</Switch>
</Layout>
);
export default App;
43
// src/components/App.js
// ...
const renderIndex = () => <IndexPage athletes={athletes} />;
const renderAthlete = ({ match, staticContext }) => {
const id = match.params.id;
const athlete = athletes.find(current => current.id === id);
if (!athlete) {
return <NotFoundPage staticContext={staticContext} />;
}
return <AthletePage
athlete={athlete}
athletes={athletes} />;
};
44
CLIENT APP
45
// src/app-client.js
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom'
import { App } from './components/App';
const AppClient = () => (
<Router>
<App />
</Router>
);
window.onload = () => {
render(
<AppClient />,
document.getElementById('main')
);
};
46
HTML TEMPLATE
47
// src/views/index.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>
Judo Heroes - A Universal JavaScript demo application with React
</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div id="main"><%- markup -%></div>
<script src="/js/bundle.js"></script>
</body>
</html>
48
BUILD CONFIG
(BABEL + WEBPACK)
49
.babelrc
import path from 'path';
const config = {
entry: {
js: './src/app-client.js',
},
output: {
path: path.join(__dirname, 'src', 'static', 'js'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: path.join(__dirname, 'src'),
use: { loader: 'babel-loader' },
},
],
},
};
.webpack.config.babel.js
{
"presets": ["react", "es2015"]
}
50
LET'S BUILD IT!
51
// src/server.js
import path from 'path';
import { Server } from 'http';
import Express from 'express';
const app = new Express();
const server = new Server(app);
// use ejs templates
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'static')));
// render the index for every non-matched route
app.get('*', (req, res) => {
let markup = '';
let status = 200;
return res.status(status).render('index', { markup });
});
// start the server
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
server.listen(port);
"Static" Express server
52
READY... LET'S TEST IT
53
RECAP
What we learned so far
1. Define views combining React components
2. Add routing using React Router
3. Compile the client bundle with Babel and
Webpack
4. Run the app with a static Express server
54
SERVER SIDE
RENDERING AND
ROUTING
55
Updating the server app
// ...
import { renderToString } from 'react-dom/server';
import { StaticRouter as Router } from 'react-router-dom';
import { App } from './components/App';
// ...
app.get('*', (req, res) => {
let markup = '';
let status = 200;
const context = {};
markup = renderToString(
<Router location={req.url} context={context}>
<App />
</Router>,
);
// context.url will contain the URL to
// redirect to if a <Redirect> was used
if (context.url) {
return res.redirect(302, context.url);
}
if (context.is404) {
status = 404;
}
return res.status(status).render('index', { markup });
});
56
THAT'S IT!
LET'S TEST AGAIN
57
RECAP
What we learned so far
1. Create a Single Page Application with
React and React Router
2. Add server side routing and rendering
using React and React Router libraries in the
Express app
58
UNIVERSAL DATA RETRIEVAL
api-proxy & async-props
(COMPLETE CHAPTER in )
UNIVERSAL STATE MANAGEMENT
Redux
Node.js Design Patterns
WHERE DO WE GO
from here...
Code: loige.link/judo-heroes-2 59
THANKS!
loige loige.colmammino
(Special thanks to , , Aleksandar Čambas & )@cirpo @andreaman87 @quasi_modal
loige.link/codemotion-rome-2017
60

More Related Content

PDF
Vue js and Vue Material
PDF
Building and deploying React applications
PPTX
Vue business first
PDF
Why Vue.js?
PDF
An introduction to Vue.js
PDF
Javascript MVVM with Vue.JS
PDF
Vue.js is boring - and that's a good thing
PDF
How to Webpack your Django!
Vue js and Vue Material
Building and deploying React applications
Vue business first
Why Vue.js?
An introduction to Vue.js
Javascript MVVM with Vue.JS
Vue.js is boring - and that's a good thing
How to Webpack your Django!

What's hot (20)

PDF
Love at first Vue
PDF
An Introduction to Django Web Framework
PDF
A Gentle Introduction to Angular Schematics - Angular SF 2019
PDF
Vue routing tutorial getting started with vue router
PDF
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
PDF
The Role of Python in SPAs (Single-Page Applications)
PDF
webcomponents (Jfokus 2015)
PDF
Testdrive AngularJS with Spring 4
PDF
Create Restful Web Application With Node.js Express Framework
PDF
How to Implement Micro Frontend Architecture using Angular Framework
PPTX
Angularjs Tutorial for Beginners
PDF
The Point of Vue - Intro to Vue.js
PPTX
Vue Introduction
PDF
125 고성능 web view-deview 2013 발표 자료_공유용
PDF
WKWebView in Production
PDF
Predictable Web Apps with Angular and Redux
PPTX
Vue js and Dyploma
PDF
The web - What it has, what it lacks and where it must go - Istanbul
PDF
Vue JS Intro
PPTX
Angular 2 어디까지 왔을까
Love at first Vue
An Introduction to Django Web Framework
A Gentle Introduction to Angular Schematics - Angular SF 2019
Vue routing tutorial getting started with vue router
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
The Role of Python in SPAs (Single-Page Applications)
webcomponents (Jfokus 2015)
Testdrive AngularJS with Spring 4
Create Restful Web Application With Node.js Express Framework
How to Implement Micro Frontend Architecture using Angular Framework
Angularjs Tutorial for Beginners
The Point of Vue - Intro to Vue.js
Vue Introduction
125 고성능 web view-deview 2013 발표 자료_공유용
WKWebView in Production
Predictable Web Apps with Angular and Redux
Vue js and Dyploma
The web - What it has, what it lacks and where it must go - Istanbul
Vue JS Intro
Angular 2 어디까지 왔을까
Ad

Viewers also liked (20)

PDF
React 101
PDF
AWS Lambda and Serverless framework: lessons learned while building a serverl...
PDF
Angular (v2 and up) - Morning to understand - Linagora
PDF
Back to the future: Isomorphic javascript applications
PDF
Quick start with React | DreamLab Academy #2
PPTX
Atomic design React Nova Presentation
PDF
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
PDF
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
PDF
Using ReactJS in AngularJS
PDF
HTML5 JavaScript APIs
PDF
Angular 2 vs React. What to chose in 2017?
PDF
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
PPTX
Combining AI and IoT. New Industrial Revolution in our houses and in the Univ...
PDF
Milano Chatbots Meetup - Vittorio Banfi - Bot Design - Codemotion Milan 2016
PPTX
Rome 2017: Building advanced voice assistants and chat bots
PDF
React JS and why it's awesome
PDF
Component Based UI Architectures for the Web
PDF
React-Native for multi-platform mobile applications @ Codemotion Rome 2017
PDF
Dx3: React for Retail
PDF
HTML5 JS APIs
React 101
AWS Lambda and Serverless framework: lessons learned while building a serverl...
Angular (v2 and up) - Morning to understand - Linagora
Back to the future: Isomorphic javascript applications
Quick start with React | DreamLab Academy #2
Atomic design React Nova Presentation
#NoXML: Eliminating XML in Spring Projects - SpringOne 2GX 2015
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Using ReactJS in AngularJS
HTML5 JavaScript APIs
Angular 2 vs React. What to chose in 2017?
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Combining AI and IoT. New Industrial Revolution in our houses and in the Univ...
Milano Chatbots Meetup - Vittorio Banfi - Bot Design - Codemotion Milan 2016
Rome 2017: Building advanced voice assistants and chat bots
React JS and why it's awesome
Component Based UI Architectures for the Web
React-Native for multi-platform mobile applications @ Codemotion Rome 2017
Dx3: React for Retail
HTML5 JS APIs
Ad

Similar to Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome 2017 (20)

PDF
Universal JavaScript - Frontend United Athens 2017
PDF
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
PDF
Introduction to React JS
PDF
Universal JS Applications with React
PDF
FRONTEND DEVELOPMENT WITH REACT.JS
PDF
Building Universal Web Apps with React ForwardJS 2017
PDF
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
PPTX
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
PPTX
React JS Unleashing the Power of Front-End Development.pptx
PPTX
Expo Router V2
PDF
ReactJS - frontend web developing reactjs
PDF
An Overview of the React Ecosystem
PDF
Creating a full stack web app with python, npm, webpack and react
PPTX
React And Express Tutorial
PPTX
INTRODUCTION TO REACT JAVASCRIPT FOR BEGINNERS.pptx
PDF
Workshop 27: Isomorphic web apps with ReactJS
PPTX
Up and Running with ReactJS
PPTX
ULTIMATE REASONS TO PREFER REACT FOR YOUR WEB DEVELOPMENT PROJECT.pptx
PPTX
why_choose_react_js_development_for_building_websites_in_2023.pptx
PPTX
Universal react
Universal JavaScript - Frontend United Athens 2017
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Introduction to React JS
Universal JS Applications with React
FRONTEND DEVELOPMENT WITH REACT.JS
Building Universal Web Apps with React ForwardJS 2017
Universal JS Web Applications with React - Web Summer Camp 2017, Rovinj (Work...
NEXTjs.pptxfggfgfdgfgfdgfdgfdgfdgfdgfdgfg
React JS Unleashing the Power of Front-End Development.pptx
Expo Router V2
ReactJS - frontend web developing reactjs
An Overview of the React Ecosystem
Creating a full stack web app with python, npm, webpack and react
React And Express Tutorial
INTRODUCTION TO REACT JAVASCRIPT FOR BEGINNERS.pptx
Workshop 27: Isomorphic web apps with ReactJS
Up and Running with ReactJS
ULTIMATE REASONS TO PREFER REACT FOR YOUR WEB DEVELOPMENT PROJECT.pptx
why_choose_react_js_development_for_building_websites_in_2023.pptx
Universal react

More from Luciano Mammino (20)

PDF
Serverless Rust: Your Low-Risk Entry Point to Rust in Production (and the ben...
PDF
Did you know JavaScript has iterators? DublinJS
PDF
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
PDF
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
PDF
From Node.js to Design Patterns - BuildPiper
PDF
Let's build a 0-cost invite-only website with Next.js and Airtable!
PDF
Everything I know about S3 pre-signed URLs
PDF
Serverless for High Performance Computing
PDF
Serverless for High Performance Computing
PDF
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
PDF
Building an invite-only microsite with Next.js & Airtable
PDF
Let's take the monolith to the cloud 🚀
PDF
A look inside the European Covid Green Certificate - Rust Dublin
PDF
Monoliths to the cloud!
PDF
The senior dev
PDF
Node.js: scalability tips - Azure Dev Community Vijayawada
PDF
A look inside the European Covid Green Certificate (Codemotion 2021)
PDF
AWS Observability Made Simple
PDF
Semplificare l'observability per progetti Serverless
PDF
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021
Serverless Rust: Your Low-Risk Entry Point to Rust in Production (and the ben...
Did you know JavaScript has iterators? DublinJS
What I learned by solving 50 Advent of Code challenges in Rust - RustNation U...
Building an invite-only microsite with Next.js & Airtable - ReactJS Milano
From Node.js to Design Patterns - BuildPiper
Let's build a 0-cost invite-only website with Next.js and Airtable!
Everything I know about S3 pre-signed URLs
Serverless for High Performance Computing
Serverless for High Performance Computing
JavaScript Iteration Protocols - Workshop NodeConf EU 2022
Building an invite-only microsite with Next.js & Airtable
Let's take the monolith to the cloud 🚀
A look inside the European Covid Green Certificate - Rust Dublin
Monoliths to the cloud!
The senior dev
Node.js: scalability tips - Azure Dev Community Vijayawada
A look inside the European Covid Green Certificate (Codemotion 2021)
AWS Observability Made Simple
Semplificare l'observability per progetti Serverless
Finding a lost song with Node.js and async iterators - NodeConf Remote 2021

Recently uploaded (20)

PDF
DevOps & Developer Experience Summer BBQ
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Advanced IT Governance
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Sensors and Actuators in IoT Systems using pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
REPORT: Heating appliances market in Poland 2024
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PPTX
Cloud computing and distributed systems.
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
DevOps & Developer Experience Summer BBQ
madgavkar20181017ppt McKinsey Presentation.pdf
Transforming Manufacturing operations through Intelligent Integrations
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
cuic standard and advanced reporting.pdf
CroxyProxy Instagram Access id login.pptx
Reimagining Insurance: Connected Data for Confident Decisions.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Advanced IT Governance
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Sensors and Actuators in IoT Systems using pdf
20250228 LYD VKU AI Blended-Learning.pptx
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
REPORT: Heating appliances market in Poland 2024
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Cloud computing and distributed systems.
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
GamePlan Trading System Review: Professional Trader's Honest Take
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”

Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome 2017