SlideShare a Scribd company logo
React Native
Developing an app similar to Uber in JavaScript
Caio Ariede
Full Stack Developer at Parasail.com
2/16/2017
github.com/caioariede
Topics
● ECMAScript 6 (es6)
● React
● React Native
● Develop an app similar to Uber
ES 6
2015
"Harmony"
ES6: Modules
// lib/math.js
export function sum (x, y) { return x + y }
export var pi = 3.141593
// someApp.js
import * as math from "lib/math"
console.log("2π = " + math.sum(math.pi, math.pi))
ES6: Classes
class Circle extends Shape {
constructor (id, x, y, radius) {
super(id, x, y)
this.radius = radius
}
}
React
React: JSX
const element = (
<h1 className="greeting">
Hello, world!
</h1>
)
React: Components
class Welcome extends React.Component {
render() {
return <h1>Welcome, {this.props.name}</h1>;
}
}
// <Welcome name="Fulano" />
React: State
class Counter extends React.Component {
state = {counter: 0}
onClick() {
this.setState({counter: this.state.counter+1})
}
render() {
return <div>
<span>{this.state.counter}</span>
<button onClick={this.onClick}>add</button>
</div>
}
}
React: VirtualDOM
Component VirtualDOM DOM (Browser)
render
React Native
React Native: Who uses?
React Native: Features
● Native apps (native UI components)
● No need to recompile every time
● Reusable code for iOS and Android (80%)
● Communication with native functions
○ Objective-C, Java
Fonte: https://speakerdeck.com/frantic/react-native-under-the-hood
React Native: Developing an app similar to Uber in JavaScript
Idea: App similar to Uber
● Login with Facebook
● Geolocation (passenger)
● Real-time updates (drivers)
● Trace/display route
● Nearest driver
Using only JavaScript
Dependencies
Getting Started
● npm install -g react-native-cli
● react-native init UberProject
● react-native run-ios
Project dependencies
● firebase: backend/database
● react-native-fbsdk: login with facebook
● react-native-maps: native map components
● geofire: location queries
● mapbox: calculate routes
React Native: Developing an app similar to Uber in JavaScript
Firebase: what's?
● Backend as a service
● Real-time database
● Handles authentication
○ oAuth, Facebook, Google, etc.
Firebase: authentication
OAuth token
Check token
Login
onClick() {
LoginManager.logInWithReadPermissions(['public_profile']).then(result => {
if (!result.isCancelled) {
} else {
console.log('login: user cancelled')
}
})
}
onClick() {
LoginManager.logInWithReadPermissions(['public_profile']).then(result => {
if (!result.isCancelled) {
AccessToken.getCurrentAccessToken().then(tokenResult => {
return auth.signInWithCredential(
facebook.credential(tokenResult.accessToken))
}).catch(err => console.log('login error: ' + err))
} else {
console.log('login: user cancelled')
}
})
}
Idea: App similar to Uber
● Login with Facebook √
● Geolocation (passenger)
● Real-time updates (drivers)
● Trace/display route
● Nearest driver
Map
class Map extends Component {
state = {
passengerPosition: {latitude: 0, longitude: 0},
}
render() {
return (
<MapView>
<Marker coordinate={this.state.passengerPosition} />
</MapView>
)
}
}
watchPassenger() {
const positionOptions = {
enableHighAccuracy: true,
}
navigator.geolocation.watchPosition(pos => {
this.updatePassengerPosition({latitude: pos.latitude,
longitude: pos.longitude})
}, positionOptions)
}
updatePassengerPosition(passengerPosition) {
this.setState({passengerPosition})
}
Geolocation
Saving location to Firebase
updatePassengerPosition(passengerPosition) {
this.setState({passengerPosition})
const user = firebase.database().ref('users/' + this.userId)
user.update({passengerPosition})
}
Idea: App similar to Uber
● Login with Facebook √
● Geolocation (passenger) √
● Real-time updates (drivers)
● Trace/display route
● Nearest driver
Real-time updates of drivers
watchDrivers() {
firebase.database().ref('drivers').on('child_changed', data => {
let drivers = this.state.drivers
drivers[driver.id] = {id: data.key, position}
this.setState({drivers})
})
}
Displaying drivers on map
renderDrivers() {
return this.state.drivers.map(driver => (
<Marker key={driver.id} coordinate={driver.position}
image={carIcon} />
))
}
Idea: App similar to Uber
● Login with Facebook √
● Geolocation (passenger) √
● Real-time updates (drivers) √
● Trace/display route
● Nearest driver
Destination
class SetDestination extends MapMixin {
constructor(props) {
this.state.destinationPosition = randomPosition(
props.passengerPosition, 500) // 500 meters
}
renderDestinationPosition() {
return <Marker draggable image={markerIcon}
coordinate={this.state.destinationPosition} />
}
}
Trace route
calculateRoute() {
const mode = 'driving'
const origin = buildLngLat(this.state.pickupPosition)
const destination = buildLngLat(this.state.destinationPosition)
const accessToken = this.mapBoxAccessToken
const url = buildMapBoxUrl(mode, origin, destination, accessToken)
fetch(url).then(response => response.json()).then(json => {
this.setState({route: getCoordinates(json)})
}).catch(e => {
console.warn(e)
})
}
Display route
renderRoute() {
return (
<MapView.Polyline strokeWidth={4}
coordinates={[this.state.passengerPosition,
...this.state.route,
this.state.destinationPosition]} />
)
}
Idea: App similar to Uber
● Login with Facebook √
● Geolocation (passenger) √
● Real-time updates (drivers) √
● Trace/display route √
● Nearest driver
GeoFire
geofire
key1: 37,-122
key2: lat, lng
key3: lat, lng
geoFire.set("key1", [37, -122])
listener geoquery
lat, lng
raio
geoquery
lat, lng
raio
Notify current geoqueries
Nearest driver
let radius = 0.1 // 100m
let currentLocation = [
passengerPosition.latitude,
passengerPosition.longitude,
]
let geoQuery = this.geoFire.query({center: currentLocation, radius})
let driversFound = []
geoQuery.on('key_entered', (key, location, distance) => {
driversFound.push({key, location, distance})
})
watchDriversFound()
Nearest driver
watchDriversFound() {
if (driversFound.length === 0) {
geoQuery.updateCriteria({radius: radius + 0.1})
} else {
let minDistance = -1, nearestDriver = null
driversFound.forEach(driver => {
if (driver.distance < minDistance || minDistance === -1)
minDistance = driver.distance, nearestDriver = driver
})
this.setState({nearestDriver: driver})
}
}
Idea: App similar to Uber
● Login with Facebook √
● Geolocation (passenger) √
● Real-time updates (drivers) √
● Trace/display route √
● Nearest driver √
Questions?
caioariede
on github and twitter

More Related Content

PDF
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
PDF
Cycle.js - A functional reactive UI framework
PDF
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
PDF
React native sharing
PDF
A tour of React Native
PPTX
SONY BBS - React Native
PPTX
Creating books app with react native
PDF
React native - What, Why, How?
Cycle.js - Functional reactive UI framework (Nikos Kalogridis)
Cycle.js - A functional reactive UI framework
React Native Introduction: Making Real iOS and Android Mobile App By JavaScript
React native sharing
A tour of React Native
SONY BBS - React Native
Creating books app with react native
React native - What, Why, How?

Viewers also liked (20)

PDF
Intro to react native
PDF
What's This React Native Thing I Keep Hearing About?
PDF
What is FED
PDF
Trend Micro Web's Scaffolding tool
PPTX
React Native for ReactJS Devs
PDF
React native redux_sharing
PDF
Comunicado a los venezolanos - Hugo Carvajal‏
PDF
React Native for Web
PDF
Dialnet filosofia delderechoencompendio-2058922
DOCX
PDF
React Native - Workshop
PDF
Introduction to React Native
PDF
Southern Traditions Outdoors July - August 2014
PDF
Southern Traditions Outdoors - November/December 2015
PDF
May - June 2016 Southern Traditions Outdoors
PDF
Getting Started with React Native (and should I use it at all?)
PDF
Cuaderno Música
PDF
Lenguaje musical 3º
PDF
Introduzione a React Native - Alessandro Giannini
PDF
When to (use / not use) React Native.
Intro to react native
What's This React Native Thing I Keep Hearing About?
What is FED
Trend Micro Web's Scaffolding tool
React Native for ReactJS Devs
React native redux_sharing
Comunicado a los venezolanos - Hugo Carvajal‏
React Native for Web
Dialnet filosofia delderechoencompendio-2058922
React Native - Workshop
Introduction to React Native
Southern Traditions Outdoors July - August 2014
Southern Traditions Outdoors - November/December 2015
May - June 2016 Southern Traditions Outdoors
Getting Started with React Native (and should I use it at all?)
Cuaderno Música
Lenguaje musical 3º
Introduzione a React Native - Alessandro Giannini
When to (use / not use) React Native.
Ad

Similar to React Native: Developing an app similar to Uber in JavaScript (20)

PPTX
React native: building shared components for Android and iOS
PDF
Philip Shurpik "Architecting React Native app"
PDF
React Native for multi-platform mobile applications
PPTX
One code Web, iOS, Android
PDF
Elevating Railway Travel Experience through React Native App Development
PPTX
React Native: Introduction
PDF
The Gist of React Native
PDF
Building React app using Test-driven Development
PDF
Burn your grass with react native
PDF
React Native: JS MVC Meetup #15
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
PPTX
React Native
PDF
Евгений Жарков "React Native: Hurdle Race"
PDF
React Native: Hurdle Race
PPTX
JS Fest 2018. Илья Иванов. Введение в React-Native
PDF
Mobile Day - React Native
PDF
React Native
PPTX
React Native - Unleash the power of React in your device - Eduard Tomàs - Cod...
PDF
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
React native: building shared components for Android and iOS
Philip Shurpik "Architecting React Native app"
React Native for multi-platform mobile applications
One code Web, iOS, Android
Elevating Railway Travel Experience through React Native App Development
React Native: Introduction
The Gist of React Native
Building React app using Test-driven Development
Burn your grass with react native
React Native: JS MVC Meetup #15
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
React Native
Евгений Жарков "React Native: Hurdle Race"
React Native: Hurdle Race
JS Fest 2018. Илья Иванов. Введение в React-Native
Mobile Day - React Native
React Native
React Native - Unleash the power of React in your device - Eduard Tomàs - Cod...
An Emoji Introduction to React Native (Panagiotis Vourtsis, Senior Front End ...
Ad

Recently uploaded (20)

PDF
Network Security Unit 5.pdf for BCA BBA.
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
KodekX | Application Modernization Development
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
DOCX
The AUB Centre for AI in Media Proposal.docx
PPT
Teaching material agriculture food technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Big Data Technologies - Introduction.pptx
Network Security Unit 5.pdf for BCA BBA.
“AI and Expert System Decision Support & Business Intelligence Systems”
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
KodekX | Application Modernization Development
Diabetes mellitus diagnosis method based random forest with bat algorithm
The AUB Centre for AI in Media Proposal.docx
Teaching material agriculture food technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Building Integrated photovoltaic BIPV_UPV.pdf
Approach and Philosophy of On baking technology
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Advanced methodologies resolving dimensionality complications for autism neur...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Big Data Technologies - Introduction.pptx

React Native: Developing an app similar to Uber in JavaScript

  • 1. React Native Developing an app similar to Uber in JavaScript
  • 2. Caio Ariede Full Stack Developer at Parasail.com 2/16/2017 github.com/caioariede
  • 3. Topics ● ECMAScript 6 (es6) ● React ● React Native ● Develop an app similar to Uber
  • 5. ES6: Modules // lib/math.js export function sum (x, y) { return x + y } export var pi = 3.141593 // someApp.js import * as math from "lib/math" console.log("2π = " + math.sum(math.pi, math.pi))
  • 6. ES6: Classes class Circle extends Shape { constructor (id, x, y, radius) { super(id, x, y) this.radius = radius } }
  • 8. React: JSX const element = ( <h1 className="greeting"> Hello, world! </h1> )
  • 9. React: Components class Welcome extends React.Component { render() { return <h1>Welcome, {this.props.name}</h1>; } } // <Welcome name="Fulano" />
  • 10. React: State class Counter extends React.Component { state = {counter: 0} onClick() { this.setState({counter: this.state.counter+1}) } render() { return <div> <span>{this.state.counter}</span> <button onClick={this.onClick}>add</button> </div> } }
  • 14. React Native: Features ● Native apps (native UI components) ● No need to recompile every time ● Reusable code for iOS and Android (80%) ● Communication with native functions ○ Objective-C, Java
  • 17. Idea: App similar to Uber ● Login with Facebook ● Geolocation (passenger) ● Real-time updates (drivers) ● Trace/display route ● Nearest driver Using only JavaScript
  • 19. Getting Started ● npm install -g react-native-cli ● react-native init UberProject ● react-native run-ios
  • 20. Project dependencies ● firebase: backend/database ● react-native-fbsdk: login with facebook ● react-native-maps: native map components ● geofire: location queries ● mapbox: calculate routes
  • 22. Firebase: what's? ● Backend as a service ● Real-time database ● Handles authentication ○ oAuth, Facebook, Google, etc.
  • 24. Login onClick() { LoginManager.logInWithReadPermissions(['public_profile']).then(result => { if (!result.isCancelled) { } else { console.log('login: user cancelled') } }) } onClick() { LoginManager.logInWithReadPermissions(['public_profile']).then(result => { if (!result.isCancelled) { AccessToken.getCurrentAccessToken().then(tokenResult => { return auth.signInWithCredential( facebook.credential(tokenResult.accessToken)) }).catch(err => console.log('login error: ' + err)) } else { console.log('login: user cancelled') } }) }
  • 25. Idea: App similar to Uber ● Login with Facebook √ ● Geolocation (passenger) ● Real-time updates (drivers) ● Trace/display route ● Nearest driver
  • 26. Map class Map extends Component { state = { passengerPosition: {latitude: 0, longitude: 0}, } render() { return ( <MapView> <Marker coordinate={this.state.passengerPosition} /> </MapView> ) } }
  • 27. watchPassenger() { const positionOptions = { enableHighAccuracy: true, } navigator.geolocation.watchPosition(pos => { this.updatePassengerPosition({latitude: pos.latitude, longitude: pos.longitude}) }, positionOptions) } updatePassengerPosition(passengerPosition) { this.setState({passengerPosition}) } Geolocation
  • 28. Saving location to Firebase updatePassengerPosition(passengerPosition) { this.setState({passengerPosition}) const user = firebase.database().ref('users/' + this.userId) user.update({passengerPosition}) }
  • 29. Idea: App similar to Uber ● Login with Facebook √ ● Geolocation (passenger) √ ● Real-time updates (drivers) ● Trace/display route ● Nearest driver
  • 30. Real-time updates of drivers watchDrivers() { firebase.database().ref('drivers').on('child_changed', data => { let drivers = this.state.drivers drivers[driver.id] = {id: data.key, position} this.setState({drivers}) }) }
  • 31. Displaying drivers on map renderDrivers() { return this.state.drivers.map(driver => ( <Marker key={driver.id} coordinate={driver.position} image={carIcon} /> )) }
  • 32. Idea: App similar to Uber ● Login with Facebook √ ● Geolocation (passenger) √ ● Real-time updates (drivers) √ ● Trace/display route ● Nearest driver
  • 33. Destination class SetDestination extends MapMixin { constructor(props) { this.state.destinationPosition = randomPosition( props.passengerPosition, 500) // 500 meters } renderDestinationPosition() { return <Marker draggable image={markerIcon} coordinate={this.state.destinationPosition} /> } }
  • 34. Trace route calculateRoute() { const mode = 'driving' const origin = buildLngLat(this.state.pickupPosition) const destination = buildLngLat(this.state.destinationPosition) const accessToken = this.mapBoxAccessToken const url = buildMapBoxUrl(mode, origin, destination, accessToken) fetch(url).then(response => response.json()).then(json => { this.setState({route: getCoordinates(json)}) }).catch(e => { console.warn(e) }) }
  • 35. Display route renderRoute() { return ( <MapView.Polyline strokeWidth={4} coordinates={[this.state.passengerPosition, ...this.state.route, this.state.destinationPosition]} /> ) }
  • 36. Idea: App similar to Uber ● Login with Facebook √ ● Geolocation (passenger) √ ● Real-time updates (drivers) √ ● Trace/display route √ ● Nearest driver
  • 37. GeoFire geofire key1: 37,-122 key2: lat, lng key3: lat, lng geoFire.set("key1", [37, -122]) listener geoquery lat, lng raio geoquery lat, lng raio Notify current geoqueries
  • 38. Nearest driver let radius = 0.1 // 100m let currentLocation = [ passengerPosition.latitude, passengerPosition.longitude, ] let geoQuery = this.geoFire.query({center: currentLocation, radius}) let driversFound = [] geoQuery.on('key_entered', (key, location, distance) => { driversFound.push({key, location, distance}) }) watchDriversFound()
  • 39. Nearest driver watchDriversFound() { if (driversFound.length === 0) { geoQuery.updateCriteria({radius: radius + 0.1}) } else { let minDistance = -1, nearestDriver = null driversFound.forEach(driver => { if (driver.distance < minDistance || minDistance === -1) minDistance = driver.distance, nearestDriver = driver }) this.setState({nearestDriver: driver}) } }
  • 40. Idea: App similar to Uber ● Login with Facebook √ ● Geolocation (passenger) √ ● Real-time updates (drivers) √ ● Trace/display route √ ● Nearest driver √