React Native
Eric Cavalcanti

@ericoc

ecavalcanti@gmail.com
O que é React Native?
O que não é React Native?
Não é híbrido!
Device API
HTML 5 e JavaScript
<!doctype html>
<html>
<body>
Content
</body>
</html>
WebView
• RN não usa WebView, a renderização é
nativa
• Perfomance do React Native tende a ser
melhor
• Os dois são OpenSource e tem um
ecossistema bem movimentado
Não é transpiled!
JavaScript
Native Code
Objective-C
Swift
Java

Kotlin…
Native App
• Nativo não tem portabilidade de código
• Desenvolvimento apenas com
linguagem nativa
• Nativo tem performance um pouco
melhor
Não é PWA!
Device API
HTML 5 e JavaScript
<!doctype html>
<html>
<body>
Content
</body>
</html>
Web Browser Container
• PWA não está na App ou Play Store
• Ainda não tem acesso a todas as
APIs e em todas as plataformas
• Sem nenhum tipo de linguagem
nativa, usa API do browser
O que é React Native?
O que é React Native?
“Learn once, write anywhere”
O que é React Native?
“Learn once, write anywhere”
Framework que permite criar aplicativos móveis
nativos utilizando JavaScript e React (Native)
Uma breve história do
React Native
Summer 2013
Facebook internal
hackathon
January 2015
Public Preview
March 2015
Released to 

open source

( iOS Support )
September 2015
Android Support
React vs React Native
ReactJS
React Component
render: function() {
return <div>Hello!</div>;
}
Browser

DOM
React

Native
React Component
render: function() {
return <View>Hello!</View>;
}
iOS
bridge
Android
???
Código Nativo iOS
// Objective-C
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:@"Alert"
message:@"Hello World"
preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];
Código Nativo iOS
// Swift
let alert = UIAlertController(title: "Alert",
message: "Hello World",
preferredStyle: .alert)
self.present(alert, animated: true)
Código Nativo Android
// Java
AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Alert");

builder.setMessage("Hello World");

builder.setPositiveButton("OK", null);

builder.show();
Código Nativo Android
// Kotlin
val builder = AlertDialog.Builder(this)
builder.setTitle("Alert")
builder.setMessage("Hello World")
builder.setPositiveButton("OK", null)
builder.show()
Com o React Native
alert('Hello World');
… e multi-plataforma!
Native - JavaScript Bridge
React Native API, Native Modules
JavaScript runtime (JavaScript Core, V8)
Application Code (JavaScript)
Native APIs
iOS, Android …
Bridge (JavaScript - Nativo)
UIButton Class
<Button title="My Button" />
Android iOS React Native
View UIView <View>
EditText UITextField <TextInput>
Por que React Native?
- experiência nativa
- uma única linguagem, JavaScript
- amigável para desenvolvedor web
- experiência de desenvolvimento rápida ( Hot Reloading, ~80% código
compartilhado, fácil debug )
- possibilita acesso a código nativo caso precise
- open source e comunidade extremamente ativa ( +57K Stars )
Por que não React Native?
- React Native é ainda relativamente novo comparado com iOS e Android
nativo
- algumas das API ainda não são suportadas por padrão ( mas é possível
acessar a API nativa através da Bridge )
- Navegação é… complexa!
- atualizações de versões constantes
- adiciona uma camada a mais
Quem usa?
Facebook Facebook Ads Manager Instagram Airbnb
Walmart Tesla
…
Skype UberEATS
SoundCloud Pulse Wix
Desenvolvimento
React = JSX + Modern JavaScript
React = JSX + Modern JavaScript
class App extends Component {
state = { text: '' };


constructor(props) {
super(props);
}
render() {
return (
<TextInput
style={{ marginTop:30, marginHorizontal:10,
height: 40, borderColor: 'gray', borderWidth: 1}}
placeholder = 'Digite seu nome'
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
);
}
}
Styles
Styles
- na web nós temos o CSS
- no React Native, nós temos algo "similar" ao CSS usando JavaScript
class LotsOfStyles extends Component {
render() {
return (
<View>
<Text style={styles.red}>just red</Text>
<Text style={styles.bigblue}>just bigblue</Text>
<Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text>
<Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text>
</View>
);
}
}
const styles = StyleSheet.create({
bigblue: {
color: 'blue',
fontWeight: 'bold',
fontSize: 30,
},
red: {
color: 'red',
},
});
Layout
Layout
buttons: {

flex: 1,

flexDirection: 'row',

justifyContent: 'space-around',

alignItems: 'center'

}
FLEXBOX
class App extends Component {
render() {
return (
<View style={{flex: 1, flexDirection: 'column', alignItems: 'center'}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>
)
}
}
class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>Hello!</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
backgroundColor: 'whitesmoke',
color: '#4A90E2',
fontSize: 24,
padding: 10,
},
})
Executando código específico para uma
Plataforma
import { Platform } from 'react-native';
if (Platform.OS === 'ios') {
...
} else {
...
}
Executando código específico para uma
Plataforma
import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
height: (Platform.OS === 'ios') ? 200 : 100,
});
Executando código específico para uma
Plataforma
import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
...Platform.select({
ios: {
backgroundColor: 'red',
},
android: {
backgroundColor: 'blue',
},
}),
},
});
Executando código específico para uma
Plataforma
const message = Platform.select({
ios: 'Hello iOS',
android: 'Hello Android',
});
Executando código específico para uma
Plataforma
const Component = Platform.select({
ios: () => require('ComponentIOS'),
android: () => require('ComponentAndroid'),
})();
<Component />;
Executando código específico para uma
Plataforma
BigButton.ios.js
BigButton.android.js
const BigButton = require('./BigButton');
Executando código específico para uma
Plataforma
spellCheck={true}
clearTextOnFocus={false}
underlineColorAndroid="transparent"
numberOfLines={2}
keyboardType="numeric"
Navigation Libs
• wix/react-native-navigation (nativo)
• airbnb/native-navigation (nativo)
• react-community/react-navigation (JS)
• aksonov/react-native-router-flux (JS - baseado no react-navigation)
Debug
• Chrome Developer Tools
• facebook/react-devtools
• jhen0409/react-native-debugger
• infinitered/reactotron
• VS Code
Como começar?
➡ react-native-cli
➡ create-react-native-app
react-native-cli
Ambiente de Desenvolvimento
Mac OS pode desenvolver
• iOS
• Android
Windows e Linux podem desenvolver
• somente Android
Instalação
MAC
HOMEBREW



/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
NODE



brew install node
WATCHMAN



brew install watchman
REACT NATIVE



npm install -g react-native-cli
Instalação
WINDOWS
CHOCOLATEY



https://chocolatey.org/
NODE



choco install nodejs.install
PYTHON 2



choco install python2
JDK 8



choco install jdk8
REACT NATIVE



npm install -g react-native-cli
SDKs
Nativos
App Store
https://developer.android.com/studio
create-react-native-app
create-react-native-app
Expo XDE
Qual editor?
• Qualquer editor de código
• Atom
• Sublime
• Visual Studio Code ❤
https://snack.expo.io/
Exemplo

React Native - JSday

  • 1.
  • 2.
    O que éReact Native?
  • 3.
    O que nãoé React Native?
  • 4.
  • 5.
    Device API HTML 5e JavaScript <!doctype html> <html> <body> Content </body> </html> WebView • RN não usa WebView, a renderização é nativa • Perfomance do React Native tende a ser melhor • Os dois são OpenSource e tem um ecossistema bem movimentado
  • 6.
  • 7.
  • 8.
    Native App • Nativonão tem portabilidade de código • Desenvolvimento apenas com linguagem nativa • Nativo tem performance um pouco melhor
  • 9.
  • 10.
    Device API HTML 5e JavaScript <!doctype html> <html> <body> Content </body> </html> Web Browser Container • PWA não está na App ou Play Store • Ainda não tem acesso a todas as APIs e em todas as plataformas • Sem nenhum tipo de linguagem nativa, usa API do browser
  • 11.
    O que éReact Native?
  • 12.
    O que éReact Native? “Learn once, write anywhere”
  • 13.
    O que éReact Native? “Learn once, write anywhere” Framework que permite criar aplicativos móveis nativos utilizando JavaScript e React (Native)
  • 14.
    Uma breve históriado React Native Summer 2013 Facebook internal hackathon January 2015 Public Preview March 2015 Released to 
 open source
 ( iOS Support ) September 2015 Android Support
  • 15.
    React vs ReactNative ReactJS React Component render: function() { return <div>Hello!</div>; } Browser
 DOM React
 Native React Component render: function() { return <View>Hello!</View>; } iOS bridge Android ???
  • 16.
    Código Nativo iOS //Objective-C UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Hello World" preferredStyle:UIAlertControllerStyleAlert]; [self presentViewController:alert animated:YES completion:nil];
  • 17.
    Código Nativo iOS //Swift let alert = UIAlertController(title: "Alert", message: "Hello World", preferredStyle: .alert) self.present(alert, animated: true)
  • 18.
    Código Nativo Android //Java AlertDialog.Builder builder = new AlertDialog.Builder(this);
 builder.setTitle("Alert");
 builder.setMessage("Hello World");
 builder.setPositiveButton("OK", null);
 builder.show();
  • 19.
    Código Nativo Android //Kotlin val builder = AlertDialog.Builder(this) builder.setTitle("Alert") builder.setMessage("Hello World") builder.setPositiveButton("OK", null) builder.show()
  • 20.
    Com o ReactNative alert('Hello World'); … e multi-plataforma!
  • 21.
    Native - JavaScriptBridge React Native API, Native Modules JavaScript runtime (JavaScript Core, V8) Application Code (JavaScript) Native APIs iOS, Android …
  • 22.
    Bridge (JavaScript -Nativo) UIButton Class <Button title="My Button" />
  • 23.
    Android iOS ReactNative View UIView <View> EditText UITextField <TextInput>
  • 24.
    Por que ReactNative? - experiência nativa - uma única linguagem, JavaScript - amigável para desenvolvedor web - experiência de desenvolvimento rápida ( Hot Reloading, ~80% código compartilhado, fácil debug ) - possibilita acesso a código nativo caso precise - open source e comunidade extremamente ativa ( +57K Stars )
  • 25.
    Por que nãoReact Native? - React Native é ainda relativamente novo comparado com iOS e Android nativo - algumas das API ainda não são suportadas por padrão ( mas é possível acessar a API nativa através da Bridge ) - Navegação é… complexa! - atualizações de versões constantes - adiciona uma camada a mais
  • 26.
    Quem usa? Facebook FacebookAds Manager Instagram Airbnb Walmart Tesla … Skype UberEATS SoundCloud Pulse Wix
  • 27.
    Desenvolvimento React = JSX+ Modern JavaScript
  • 28.
    React = JSX+ Modern JavaScript class App extends Component { state = { text: '' }; 
 constructor(props) { super(props); } render() { return ( <TextInput style={{ marginTop:30, marginHorizontal:10, height: 40, borderColor: 'gray', borderWidth: 1}} placeholder = 'Digite seu nome' onChangeText={(text) => this.setState({text})} value={this.state.text} /> ); } }
  • 29.
  • 30.
    Styles - na webnós temos o CSS - no React Native, nós temos algo "similar" ao CSS usando JavaScript class LotsOfStyles extends Component { render() { return ( <View> <Text style={styles.red}>just red</Text> <Text style={styles.bigblue}>just bigblue</Text> <Text style={[styles.bigblue, styles.red]}>bigblue, then red</Text> <Text style={[styles.red, styles.bigblue]}>red, then bigblue</Text> </View> ); } } const styles = StyleSheet.create({ bigblue: { color: 'blue', fontWeight: 'bold', fontSize: 30, }, red: { color: 'red', }, });
  • 31.
  • 32.
    Layout buttons: {
 flex: 1,
 flexDirection:'row',
 justifyContent: 'space-around',
 alignItems: 'center'
 } FLEXBOX
  • 33.
    class App extendsComponent { render() { return ( <View style={{flex: 1, flexDirection: 'column', alignItems: 'center'}}> <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} /> <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} /> <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} /> </View> ) } }
  • 34.
    class App extendsComponent { render() { return ( <View style={styles.container}> <Text style={styles.text}>Hello!</Text> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, text: { backgroundColor: 'whitesmoke', color: '#4A90E2', fontSize: 24, padding: 10, }, })
  • 35.
    Executando código específicopara uma Plataforma import { Platform } from 'react-native'; if (Platform.OS === 'ios') { ... } else { ... }
  • 36.
    Executando código específicopara uma Plataforma import { Platform, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ height: (Platform.OS === 'ios') ? 200 : 100, });
  • 37.
    Executando código específicopara uma Plataforma import { Platform, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, ...Platform.select({ ios: { backgroundColor: 'red', }, android: { backgroundColor: 'blue', }, }), }, });
  • 38.
    Executando código específicopara uma Plataforma const message = Platform.select({ ios: 'Hello iOS', android: 'Hello Android', });
  • 39.
    Executando código específicopara uma Plataforma const Component = Platform.select({ ios: () => require('ComponentIOS'), android: () => require('ComponentAndroid'), })(); <Component />;
  • 40.
    Executando código específicopara uma Plataforma BigButton.ios.js BigButton.android.js const BigButton = require('./BigButton');
  • 41.
    Executando código específicopara uma Plataforma spellCheck={true} clearTextOnFocus={false} underlineColorAndroid="transparent" numberOfLines={2} keyboardType="numeric"
  • 42.
    Navigation Libs • wix/react-native-navigation(nativo) • airbnb/native-navigation (nativo) • react-community/react-navigation (JS) • aksonov/react-native-router-flux (JS - baseado no react-navigation)
  • 43.
    Debug • Chrome DeveloperTools • facebook/react-devtools • jhen0409/react-native-debugger • infinitered/reactotron • VS Code
  • 44.
  • 45.
  • 46.
    Ambiente de Desenvolvimento MacOS pode desenvolver • iOS • Android Windows e Linux podem desenvolver • somente Android
  • 47.
    Instalação MAC HOMEBREW
 
 /usr/bin/ruby -e "$(curl-fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" NODE
 
 brew install node WATCHMAN
 
 brew install watchman REACT NATIVE
 
 npm install -g react-native-cli
  • 48.
    Instalação WINDOWS CHOCOLATEY
 
 https://chocolatey.org/ NODE
 
 choco install nodejs.install PYTHON2
 
 choco install python2 JDK 8
 
 choco install jdk8 REACT NATIVE
 
 npm install -g react-native-cli
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
    Qual editor? • Qualquereditor de código • Atom • Sublime • Visual Studio Code ❤
  • 54.
  • 55.