SlideShare a Scribd company logo
CREATING A FULL STACK WEB APP WITH
PYTHON, NPM, WEBPACK AND REACT
by Angela Branaes
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
THE STRUCTURE OF A WEB APP
➤ Separated into front and back end.
➤ Multiple technologies.
➤ Front end is:
➤ Look and feel.
➤ User interaction.
➤ Back end is:
➤ Long running operations.
➤ Data, and data processing.
➤ Application logic.
INITIAL PROJECT SETUP
➤ Create the following directory structure
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
└── js/
$ cd fullstack_template/static
WE’RE GOING TO NEED A JAVASCRIPT PACKAGE MANAGER
➤ Using a package manager makes it painless to:

➤ Keep your project dependencies up to date.

➤ Fetch and install new packages.

➤ Similar to brew, pip, pacman etc.
NPM
NPM = NODE PACKAGE MANAGER
➤ Automatically included with Node.js

➤ Easy to use

➤ well documented

➤ nearly 500 000 packages available

➤ Initialise NPM:

$ npm init
➤ This creates a file called package.json
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
└── package.json
THE PURPOSE OF PACKAGE.JSON
1. Keeps track of dependencies and versions.

2. Informs other developers about your project.

3. Makes installing, running and updating a project automatic and reproducible
THIS IS MY PACKAGE.JSON
{
"name": "FullStackTemplate",
"version": "1.0.0",
"description": "Fullstack Template",
"main": "index.jsx",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
},
"keywords": [
"python",
"react",
"npm",
"webpack"
],
"author": "Angela Branaes",
"license": "MIT",
"devDependencies": {
"webpack": "^3.0.0"
}
}
WHY WE NEED A MODULE BUNDLER
➤ Minimises the number of <script> tags in your HTML
➤ This means faster loading, and less hassle.
➤ Don’t need to worry about bundle import ordering!
➤ Don’t have to use globals or namespacing.
➤ Lazy module loading.
➤ We will be using Webpack.
WEBPACK
WEBPACK
➤ Only understands JavaScript.
➤ Everything else needs a loader or plugin.
➤ Everything is a module.
➤ You can require() JavaScript, React, CSS or images.
➤ Creates a dependency tree of all your required modules, and packages those into
bundles.
➤ Easy to get started with, if you only need JavaScript.
➤ Minor learning curve for css/less and image loading.
➤ Lets you split your bundles and load them asynchronously and lazily.
➤ Integrates seamlessly with npm.
INSTALL & CONFIGURE WEBPACK
➤ Install webpack:
$ npm i webpack --save-dev
➤ Add a file named webpack.config.js:
const webpack = require(‘webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
};
module.exports = config;
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
├── package.json
└── webpack.config.js
SINGLE VS MULTI PAGE APPLICATIONS
➤ I mostly use Webpack for single page applications.
➤ You can also use webpack for multi page applications:
entry: {

“indexPage”: __dirname + “js/index.jsx”,

“aboutPage”: __dirname + “js/about.jsx”
},
output: {
path: __dirname + “/dist”,

filename: “[name].js” //e.g. aboutPage.js
}
LET’S DISPLAY AN ALERT!
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
│ └── bundle.js
├── images/
├── js/
│ └── index.jsx
├── index.html
├── package.json
└── webpack.config.js
CREATE INDEX.HTML
➤ A really simple index.html is all you need.
➤ The index.html just loads your JavaScript bundle
<body>
<div id="content" />
<script src="dist/bundle.js" type=“text/javascript”>
</script>
</body>
➤ All the layout and behaviour live in the JS/React files!
CREATE INDEX.JSX
➤ Just 1 line of Plain Old JavaScript
alert(“Hello World!”);
BUILDING YOUR APPLICATION
➤ Create run commands to simplify building your code.
➤ Run commands are just aliases.
➤ Example from my package.json:
“scripts": {
"watch": "webpack --progress -d --config webpack.config.js —watch"
}
➤ Makes the dev process more fluid.
➤ I always add the following:
➤ build
➤ dev-build
➤ watch
START THE WATCH COMMAND
➤ Any changes get built automatically
$ npm run watch
➤ Open index.html….
Creating a full stack web app with python, npm, webpack and react
CREATING A SIMPLE REACT APP
THE BENEFITS OF USING REACT
➤ Easy to build UIs composed of small, distinct components.
➤ Encourages design of reusable UI components.
➤ Easier to understand what’s going on when markup lives with the code (JSX).
➤ Automatic re-rendering of components on change.
➤ Easy to maintain.
INSTALL REACT
$ npm i react react-dom —save-dev
REACTIFY INDEX.JSX
import React from "react";
import ReactDOM from "react-dom";
import App from “./App";
ReactDOM.render(<App />, document.getElementById("content"));
ADD A REACT “APP” CLASS
➤ Remember to export your react classes!
// App.jsx
import React from “react”;
export default class App extends React.Component {
render () {
return <p> Hello React!</p>;
}
}
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ └── App.jsx
├── index.html
├── package.json
└── webpack.config.js
WHAT IS JSX?
➤ Syntax extension to JavaScript.
➤ Optimised on compilation, so faster than JavaScript.
➤ Statically typed and mostly type-safe. JavaScript is not.
➤ Lets you write HTML tags in your JavaScript functions:
<Hello name=“Rimini” />
instead of
React.createElement(Hello, {name: “Rimini}, null)
➤ Recognises upper-case element-types as written in React. E.g. <Hello />
➤ How do we make our browser understand JSX?
INTRODUCING BABEL
Write next-generation javascript right now!
Transform JSX to JS.
ADD BABEL
➤ Install Babel
➤ Add the Babel presets to the package.json:
“babel”: {
“presets”: [
“es2015”,
“react”
]
},
ADD A BABEL-LOADER RULE TO THE WEBPACK CONFIG:
module: {
rules: [
{
test: /.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
OPEN INDEX.HTML IN YOUR BROWSER
➤ This should now show the “Hello React” paragraph we added in our new React
App.jsx file.
Creating a full stack web app with python, npm, webpack and react
PYTHON FLASK SERVER
PYTHON
➤ Go to the server folder
➤ Ensure you’re in a Python virtualenv
$ mkvirtualenv fullstack
➤ Install Flask
(fullstack)$ pip install flask
➤ Create a file called server.py in the server folder
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ └── App.jsx
├── index.html
├── package.json
└── webpack.config.js
SERVER.PY
from flask import Flask, render_template
app = Flask(__name__, static_folder=“../static/dist",
template_folder="../static")
@app.route("/")
def index():
return render_template("index.html")
@app.route("/hello")
def hello():
return "Hello World!”
if __name__ == "__main__":
app.run()
START THE SERVER
➤ Go to: http://localhost:5000/
$ python server.py
REQUEST INFO FROM THE SERVER
var $ = require(‘jquery');
getPythonHello() {
$.get(window.location.href + 'hello', (data) => {
console.log(data);
this.personaliseGreeting(data);
});
}
MAKE PYTHON DO SOMETHING MORE INTERESTING
➤ We call get_hello() whenever we hit the /hello endpoint
def get_hello():
greeting_list = ['Ciao', 'Hei', 'Salut', 'Hola', 'Hallo', 'Hej']
return random.choice(greeting_list)
SAY HI TO SOMEONE SPECIAL
➤ There should be a class for that!

➤ Change the App.jsx render method to the following:

render () {
return (
<PageHeader>
<div className='header-contents'>
<Hello name='Rimini' />
</div>
</PageHeader>
);
)
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
├── dist/
├── images/
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
CREATE THE HELLO CLASS
export default class Hello extends React.Component {
constructor(props) {
super(props);
// greeting is now “Hello Rimini”
this.state = {greeting: 'Hello ' + this.props.name};
// This binding is necessary to make `this`
// work in the button callback
this.getPythonHello = this.getPythonHello.bind(this);
}
}
➤ Add this function to the Hello class:
➤ This will re-render the greeting on our website to a new one when called.
personaliseGreeting(greeting) {
this.setState({greeting: greeting + ' ' + this.props.name + '!'});
}
LET’S FINALLY RENDER OUR HELLO!
render () {
return (
<h1>{this.state.greeting}</h1>
<hr/>
<Button onClick={this.getPythonHello}>
Say Hello!
</Button>
);
}
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
CREATE A NICE LAYOUT WITH CSS
➤ Webpack ONLY understands JavaScript.
➤ Install the following loaders and plugins:
➤ style-loader
➤ css-loader
➤ extract-text-webpack-plugin
➤ Add a plugin to the webpack config:
plugins: [
new ExtractTextPlugin('styles.css'),
]
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
│ └── fullstack.css
├── dist/
│ ├── bundle.js
│ └── styles.css
├── images/
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
➤ Add fullstack.css to the css folder
➤ Add a few css rules for our header
➤ require fullstack.css in App.jsx:
require(‘../css/fullstack.css');
➤ Add the bundled css to the index.html:
<link rel="stylesheet" href="dist/styles.css">
Creating a full stack web app with python, npm, webpack and react
OUR UPDATED DIRECTORY TREE
.
├── README.md
└── fullstack_template/
├── server/
│ └── server.py
└── static/
├── css/
│ └── fullstack.css
├── dist/
│ ├── bundle.js
│ └── styles.css
├── images/
│ └── header.png
├── js/
│ ├── index.jsx
│ ├── App.jsx
│ └── Hello.jsx
├── index.html
├── package.json
└── webpack.config.js
ADD A NICE BACKGROUND IMAGE
1. Add the file-loader loader
2. Add an image to your images/ folder
3. Set the image to be your header background in the fullstack.css file
background-image: url(‘../images/header.jpg’);
4. NOTE: you have to load the image in your React app for it to show up!
IN APP.JSX
import HeaderBackgroundImage from ‘../images/header.jpg’;
➤ Add this fn to your class:
addHeaderImg() {
let headerBg = new Image();
headerBg.src = HeaderBackgroundImage;
}
➤ And this to your render():
{this.addHeaderImg()}
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
THANK YOU! ANY QUESTIONS?
@angineering
@angineering - The code is on GitHub:
https://github.com/angineering/FullStackTemplate
@angineering - This talk is also a blogpost

More Related Content

PDF
PHP SA 2014 - Releasing Your Open Source Project
PDF
BaláZs Ree Introduction To Kss, Kinetic Style Sheets
PDF
Developers, Be a Bada$$ with WP-CLI
PDF
Martin Aspeli Extending And Customising Plone 3
PDF
Jenkins Setup Document
PPT
D installation manual
PPTX
2015 - Basta! 2015, DE: JavaScript und build
PPTX
WordCamp Ann Arbor 2015 Introduction to Backbone + WP REST API
PHP SA 2014 - Releasing Your Open Source Project
BaláZs Ree Introduction To Kss, Kinetic Style Sheets
Developers, Be a Bada$$ with WP-CLI
Martin Aspeli Extending And Customising Plone 3
Jenkins Setup Document
D installation manual
2015 - Basta! 2015, DE: JavaScript und build
WordCamp Ann Arbor 2015 Introduction to Backbone + WP REST API

What's hot (20)

PPTX
Vagrant crash course
PDF
WPDay Bologna 2013
PDF
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
PDF
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
PDF
PDF
Hitchhiker's guide to the front end development
PPTX
Front end performance optimization
KEY
PDF
Front End Performance
PDF
GlassFish Embedded API
PDF
Vagrant for real codemotion (moar tips! ;-))
PDF
Introduction to Webpack - Ordina JWorks - CC JS & Web
PDF
Vagrant for Virtualized Development
PDF
Rock-solid Magento Development and Deployment Workflows
PDF
Front end performance tip
PDF
WebPagetest Power Users - Velocity 2014
PPTX
Node JS Express : Steps to Create Restful Web App
PPTX
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
PDF
Single page apps with drupal 7
PDF
Pyramid Deployment and Maintenance
Vagrant crash course
WPDay Bologna 2013
Fast Paced Drupal 8: Accelerating Development with Composer, Drupal Console a...
Godefroid Chapelle Ajax With Plone 3 Kss Development Patterns
Hitchhiker's guide to the front end development
Front end performance optimization
Front End Performance
GlassFish Embedded API
Vagrant for real codemotion (moar tips! ;-))
Introduction to Webpack - Ordina JWorks - CC JS & Web
Vagrant for Virtualized Development
Rock-solid Magento Development and Deployment Workflows
Front end performance tip
WebPagetest Power Users - Velocity 2014
Node JS Express : Steps to Create Restful Web App
#3 Hanoi Magento Meetup - Part 2: Scalable Magento Development With Containers
Single page apps with drupal 7
Pyramid Deployment and Maintenance
Ad

Similar to Creating a full stack web app with python, npm, webpack and react (20)

PPTX
WEBPACK
PDF
How to Webpack your Django!
PDF
Webpack presentation
PPTX
Improving build solutions dependency management with webpack
PDF
Nuxtjs cheat-sheet
PPTX
Ultimate Survival - React-Native edition
PDF
ReactJS Workflows
PDF
Introduction of webpack 4
PDF
Modern Web Application Development Workflow - EclipseCon Europe 2014
PDF
Magento 2 Development
PDF
Zero Downtime Deployment with Ansible
PPTX
2019 Chef InSpec Jumpstart Part 2 of 2
PDF
Modern Web Application Development Workflow - EclipseCon France 2014
PPTX
How to install ReactJS software
PPTX
ReactJS software installation
PDF
Zero Downtime Deployment with Ansible
PDF
Room with a Vue - Introduction to Vue.js
PPTX
Getting Started with React v16
PDF
Love at first Vue
WEBPACK
How to Webpack your Django!
Webpack presentation
Improving build solutions dependency management with webpack
Nuxtjs cheat-sheet
Ultimate Survival - React-Native edition
ReactJS Workflows
Introduction of webpack 4
Modern Web Application Development Workflow - EclipseCon Europe 2014
Magento 2 Development
Zero Downtime Deployment with Ansible
2019 Chef InSpec Jumpstart Part 2 of 2
Modern Web Application Development Workflow - EclipseCon France 2014
How to install ReactJS software
ReactJS software installation
Zero Downtime Deployment with Ansible
Room with a Vue - Introduction to Vue.js
Getting Started with React v16
Love at first Vue
Ad

Recently uploaded (20)

DOCX
The Five Best AI Cover Tools in 2025.docx
PDF
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PDF
System and Network Administraation Chapter 3
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
System and Network Administration Chapter 2
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
PDF
Digital Strategies for Manufacturing Companies
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Become an Agentblazer Champion Challenge
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PDF
AI in Product Development-omnex systems
PDF
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
PPTX
Save Business Costs with CRM Software for Insurance Agents
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
PPTX
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
The Five Best AI Cover Tools in 2025.docx
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
Best Practices for Rolling Out Competency Management Software.pdf
System and Network Administraation Chapter 3
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Become an Agentblazer Champion Challenge Kickoff
System and Network Administration Chapter 2
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
Digital Strategies for Manufacturing Companies
PTS Company Brochure 2025 (1).pdf.......
Become an Agentblazer Champion Challenge
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
AI in Product Development-omnex systems
Perfecting Gamer’s Experiences with Performance Testing for Gaming Applicatio...
Save Business Costs with CRM Software for Insurance Agents
How to Migrate SBCGlobal Email to Yahoo Easily
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
QAware_Mario-Leander_Reimer_Architecting and Building a K8s-based AI Platform...
Mastering-Cybersecurity-The-Crucial-Role-of-Antivirus-Support-Services.pptx
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...

Creating a full stack web app with python, npm, webpack and react

  • 1. CREATING A FULL STACK WEB APP WITH PYTHON, NPM, WEBPACK AND REACT by Angela Branaes
  • 6. THE STRUCTURE OF A WEB APP ➤ Separated into front and back end. ➤ Multiple technologies. ➤ Front end is: ➤ Look and feel. ➤ User interaction. ➤ Back end is: ➤ Long running operations. ➤ Data, and data processing. ➤ Application logic.
  • 7. INITIAL PROJECT SETUP ➤ Create the following directory structure . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ └── js/ $ cd fullstack_template/static
  • 8. WE’RE GOING TO NEED A JAVASCRIPT PACKAGE MANAGER ➤ Using a package manager makes it painless to: ➤ Keep your project dependencies up to date. ➤ Fetch and install new packages. ➤ Similar to brew, pip, pacman etc.
  • 9. NPM
  • 10. NPM = NODE PACKAGE MANAGER ➤ Automatically included with Node.js ➤ Easy to use ➤ well documented ➤ nearly 500 000 packages available ➤ Initialise NPM: $ npm init ➤ This creates a file called package.json
  • 11. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ └── package.json
  • 12. THE PURPOSE OF PACKAGE.JSON 1. Keeps track of dependencies and versions. 2. Informs other developers about your project. 3. Makes installing, running and updating a project automatic and reproducible
  • 13. THIS IS MY PACKAGE.JSON { "name": "FullStackTemplate", "version": "1.0.0", "description": "Fullstack Template", "main": "index.jsx", "scripts": { "test": "echo "Error: no test specified" && exit 1", }, "keywords": [ "python", "react", "npm", "webpack" ], "author": "Angela Branaes", "license": "MIT", "devDependencies": { "webpack": "^3.0.0" } }
  • 14. WHY WE NEED A MODULE BUNDLER ➤ Minimises the number of <script> tags in your HTML ➤ This means faster loading, and less hassle. ➤ Don’t need to worry about bundle import ordering! ➤ Don’t have to use globals or namespacing. ➤ Lazy module loading. ➤ We will be using Webpack.
  • 16. WEBPACK ➤ Only understands JavaScript. ➤ Everything else needs a loader or plugin. ➤ Everything is a module. ➤ You can require() JavaScript, React, CSS or images. ➤ Creates a dependency tree of all your required modules, and packages those into bundles. ➤ Easy to get started with, if you only need JavaScript. ➤ Minor learning curve for css/less and image loading. ➤ Lets you split your bundles and load them asynchronously and lazily. ➤ Integrates seamlessly with npm.
  • 17. INSTALL & CONFIGURE WEBPACK ➤ Install webpack: $ npm i webpack --save-dev ➤ Add a file named webpack.config.js: const webpack = require(‘webpack'); const config = { entry: __dirname + '/js/index.jsx', output: { path: __dirname + '/dist', filename: 'bundle.js', }, resolve: { extensions: ['.js', '.jsx', '.css'] }, }; module.exports = config;
  • 18. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ ├── package.json └── webpack.config.js
  • 19. SINGLE VS MULTI PAGE APPLICATIONS ➤ I mostly use Webpack for single page applications. ➤ You can also use webpack for multi page applications: entry: {
 “indexPage”: __dirname + “js/index.jsx”,
 “aboutPage”: __dirname + “js/about.jsx” }, output: { path: __dirname + “/dist”,
 filename: “[name].js” //e.g. aboutPage.js }
  • 21. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ │ └── bundle.js ├── images/ ├── js/ │ └── index.jsx ├── index.html ├── package.json └── webpack.config.js
  • 22. CREATE INDEX.HTML ➤ A really simple index.html is all you need. ➤ The index.html just loads your JavaScript bundle <body> <div id="content" /> <script src="dist/bundle.js" type=“text/javascript”> </script> </body> ➤ All the layout and behaviour live in the JS/React files!
  • 23. CREATE INDEX.JSX ➤ Just 1 line of Plain Old JavaScript alert(“Hello World!”);
  • 24. BUILDING YOUR APPLICATION ➤ Create run commands to simplify building your code. ➤ Run commands are just aliases. ➤ Example from my package.json: “scripts": { "watch": "webpack --progress -d --config webpack.config.js —watch" } ➤ Makes the dev process more fluid. ➤ I always add the following: ➤ build ➤ dev-build ➤ watch
  • 25. START THE WATCH COMMAND ➤ Any changes get built automatically $ npm run watch ➤ Open index.html….
  • 27. CREATING A SIMPLE REACT APP
  • 28. THE BENEFITS OF USING REACT ➤ Easy to build UIs composed of small, distinct components. ➤ Encourages design of reusable UI components. ➤ Easier to understand what’s going on when markup lives with the code (JSX). ➤ Automatic re-rendering of components on change. ➤ Easy to maintain.
  • 29. INSTALL REACT $ npm i react react-dom —save-dev
  • 30. REACTIFY INDEX.JSX import React from "react"; import ReactDOM from "react-dom"; import App from “./App"; ReactDOM.render(<App />, document.getElementById("content"));
  • 31. ADD A REACT “APP” CLASS ➤ Remember to export your react classes! // App.jsx import React from “react”; export default class App extends React.Component { render () { return <p> Hello React!</p>; } }
  • 32. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ └── App.jsx ├── index.html ├── package.json └── webpack.config.js
  • 33. WHAT IS JSX? ➤ Syntax extension to JavaScript. ➤ Optimised on compilation, so faster than JavaScript. ➤ Statically typed and mostly type-safe. JavaScript is not. ➤ Lets you write HTML tags in your JavaScript functions: <Hello name=“Rimini” /> instead of React.createElement(Hello, {name: “Rimini}, null) ➤ Recognises upper-case element-types as written in React. E.g. <Hello /> ➤ How do we make our browser understand JSX?
  • 34. INTRODUCING BABEL Write next-generation javascript right now! Transform JSX to JS.
  • 35. ADD BABEL ➤ Install Babel ➤ Add the Babel presets to the package.json: “babel”: { “presets”: [ “es2015”, “react” ] },
  • 36. ADD A BABEL-LOADER RULE TO THE WEBPACK CONFIG: module: { rules: [ { test: /.jsx?/, exclude: /node_modules/, use: 'babel-loader' } ] }
  • 37. OPEN INDEX.HTML IN YOUR BROWSER ➤ This should now show the “Hello React” paragraph we added in our new React App.jsx file.
  • 40. PYTHON ➤ Go to the server folder ➤ Ensure you’re in a Python virtualenv $ mkvirtualenv fullstack ➤ Install Flask (fullstack)$ pip install flask ➤ Create a file called server.py in the server folder
  • 41. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ └── App.jsx ├── index.html ├── package.json └── webpack.config.js
  • 42. SERVER.PY from flask import Flask, render_template app = Flask(__name__, static_folder=“../static/dist", template_folder="../static") @app.route("/") def index(): return render_template("index.html") @app.route("/hello") def hello(): return "Hello World!” if __name__ == "__main__": app.run()
  • 43. START THE SERVER ➤ Go to: http://localhost:5000/ $ python server.py
  • 44. REQUEST INFO FROM THE SERVER var $ = require(‘jquery'); getPythonHello() { $.get(window.location.href + 'hello', (data) => { console.log(data); this.personaliseGreeting(data); }); }
  • 45. MAKE PYTHON DO SOMETHING MORE INTERESTING ➤ We call get_hello() whenever we hit the /hello endpoint def get_hello(): greeting_list = ['Ciao', 'Hei', 'Salut', 'Hola', 'Hallo', 'Hej'] return random.choice(greeting_list)
  • 46. SAY HI TO SOMEONE SPECIAL ➤ There should be a class for that! ➤ Change the App.jsx render method to the following: render () { return ( <PageHeader> <div className='header-contents'> <Hello name='Rimini' /> </div> </PageHeader> ); )
  • 47. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ ├── dist/ ├── images/ ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 48. CREATE THE HELLO CLASS export default class Hello extends React.Component { constructor(props) { super(props); // greeting is now “Hello Rimini” this.state = {greeting: 'Hello ' + this.props.name}; // This binding is necessary to make `this` // work in the button callback this.getPythonHello = this.getPythonHello.bind(this); } }
  • 49. ➤ Add this function to the Hello class: ➤ This will re-render the greeting on our website to a new one when called. personaliseGreeting(greeting) { this.setState({greeting: greeting + ' ' + this.props.name + '!'}); }
  • 50. LET’S FINALLY RENDER OUR HELLO! render () { return ( <h1>{this.state.greeting}</h1> <hr/> <Button onClick={this.getPythonHello}> Say Hello! </Button> ); }
  • 53. CREATE A NICE LAYOUT WITH CSS ➤ Webpack ONLY understands JavaScript. ➤ Install the following loaders and plugins: ➤ style-loader ➤ css-loader ➤ extract-text-webpack-plugin ➤ Add a plugin to the webpack config: plugins: [ new ExtractTextPlugin('styles.css'), ]
  • 54. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ │ └── fullstack.css ├── dist/ │ ├── bundle.js │ └── styles.css ├── images/ ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 55. ➤ Add fullstack.css to the css folder ➤ Add a few css rules for our header ➤ require fullstack.css in App.jsx: require(‘../css/fullstack.css'); ➤ Add the bundled css to the index.html: <link rel="stylesheet" href="dist/styles.css">
  • 57. OUR UPDATED DIRECTORY TREE . ├── README.md └── fullstack_template/ ├── server/ │ └── server.py └── static/ ├── css/ │ └── fullstack.css ├── dist/ │ ├── bundle.js │ └── styles.css ├── images/ │ └── header.png ├── js/ │ ├── index.jsx │ ├── App.jsx │ └── Hello.jsx ├── index.html ├── package.json └── webpack.config.js
  • 58. ADD A NICE BACKGROUND IMAGE 1. Add the file-loader loader 2. Add an image to your images/ folder 3. Set the image to be your header background in the fullstack.css file background-image: url(‘../images/header.jpg’); 4. NOTE: you have to load the image in your React app for it to show up!
  • 59. IN APP.JSX import HeaderBackgroundImage from ‘../images/header.jpg’; ➤ Add this fn to your class: addHeaderImg() { let headerBg = new Image(); headerBg.src = HeaderBackgroundImage; } ➤ And this to your render(): {this.addHeaderImg()}
  • 64. THANK YOU! ANY QUESTIONS? @angineering @angineering - The code is on GitHub: https://github.com/angineering/FullStackTemplate @angineering - This talk is also a blogpost