React Native - JSday

Post on 22-Jan-2018

305 views 2 download

Transcript of React Native - JSday

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!

JavaScriptNative 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>;}

BrowserDOM

ReactNative

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)"

NODEbrew install node

WATCHMANbrew install watchman

REACT NATIVEnpm install -g react-native-cli

Instalação WINDOWS

CHOCOLATEYhttps://chocolatey.org/

NODEchoco install nodejs.install

PYTHON 2choco install python2

JDK 8choco install jdk8

REACT NATIVEnpm install -g react-native-cli

SDKs Nativos

App Storehttps://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