ReactNativena
globo.com
Webdeveloperhá7anos
4anosemeionaglobo.com.
Globoesporte,Home,NavegaçãoeApps.
Guilherme
Bruzzi
ambienteda
globo.com
• Grandes portais com mais de 50 milhões de
acessos diários
• Muitos programadores web que adoram JS e
mais recentemente React
• Nós amamos open source!
opensource.globo.com
equipe de
produtos
ambienteda
globo.com
ge gshow
g1tt
equipe de
plataformas
oproblemadasapps
dagcom
• Problema atual: Todas em webview
• One app to rule them all
392 × 690392 × 690
oproblemadasapps
dagcom
oproblemadasapps
dagcom
• Primeira App em RN: Techtudo (depois g1, gshow e ge)
• Um feed nativo para consumir matérias
appshíbridas
• Soluções Webview como Cordova / Phonegap /
ionic
• Reaproveitamento de código forte
• Problemas da Webview
• “Cross-browser"
códigonativo
• Objective-C / Swift para iOS
• Java para Android
• Perfomance otimizada
• 2 códigos para as mesmas regras de negócio
pocnativo
• 1 semana para iOS
• 1 semana para Android
xamarin
• C# com Mono .NET framework e IDE própria
• Compilado para interagir com o Java e Obj-C
• Reaproveitamento de código
react
• Lib criada em 2013 pelo Facebook
• Performance na escrita de mudanças
• Componentização por padrão
• Comunidade ativa e open source
exemploreact
• Criado com create-react-app
1. Estilo inline
2. Props
3. State
npm install -g create-react-app
create-react-app my-app
reactplataformas
reactplataformas
• “learn once, write everywhere”:
1. Android (suporte Padrão)
2. iOS (suporte Padrão)
3. Windows: https://github.com/ReactWindows/
react-native-windows
4. Ubuntu: https://github.com/CanonicalLtd/
react-native
reactnative
• Criado em 2015
• JS e React
• Estilo via dialeto de CSS / Flexbox
• Performance nativa
• Não usa webview
• Reaproveitamento de código cross-plataforma
pocreactnative
• 2 semanas para os dois (código único)
Muitoobrigado!
=)
reactnative
arquitetura
• nenhuma webview
• Thread JS (webkit)
• Shadow Queue
• Main e threads Nativa (inclui UI)
• Mais profundamente em: https://www.youtube.com/
watch?v=Ah2qNbI40vE (Tadeu Zagallo)
reactnative
arquitetura
• Códigos: https://github.com/guilhermebruzzi/rnExamples
• Exemplo geral
1. Hello World + Reload e hot reload
2. Componentes padrões: Textos, imagens e ListView
3. Routers que usamos
reactnative
exemplos
• Linter (Eslint airbnb)
• Flow (vs typescript)
• Mobx (vs Redux)
• RN Router Flux/ Mobx
Router
• Webview Bridge
• Urban Airship
• ES6 fetch
• Code Push
• Fabric
reactnativeconfig
nagcom
rnconfig
rnrouterflux/mobxrouter
• React Native router flux:
https://github.com/aksonov/react-native-router-flux
• React Native mobx:
https://github.com/aksonov/react-native-mobx
rnconfig
linter
• Linter (Eslint extendendo eslint-config-airbnb)
• Erros na hora
Tipagem no meio do javascript
// @flow
const foo = (b: boolean): string => (
(b) ? 'Hello' : 'World'
);
const bar: string = foo();
rnconfig
flow
const { action, observable } = mobx;
const { observer } = mobxReact;
class CountStore {
@observable count = 0;
@action addCount() { this.count++; }
@action decCount() { this.count--; }
}
const store = new CountStore();
@observer
class App extends React.Component {
render() {
return (
<div>
<span>Contador: {store.count}</span>
<button onClick={() => store.addCount()}> + </button>
<button onClick={() => store.decCount()}> - </button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
rnconfig
mobx
Controle de estado global (https://jsbin.com/qizehep)
const injectScript = `
WebViewBridge.onMessage = function (message) {
console.log('Received from react native', message);
};
WebViewBridge.send('hello from webview');
`;
class App extends React.Component {
onBridgeMessage(message) {
const { webviewbridge } = this.refs;
console.log('Received from webview', message);
webviewbridge.sendToBridge("hello from react-native");
}
render() {
return (
<WebViewBridge
ref="webviewbridge"
onBridgeMessage={this.onBridgeMessage.bind(this)}
injectedJavaScript={injectScript}
source={{uri: "http://google.com"}}/>
);
}
}
rnconfig
webviewbridge
React Native Webview Bridge: https://github.com/alinz/react-native-webview-bridge
import ReactNativeUA from 'react-native-ua';
class App extends Component {
constructor(props) {
super(props);
ReactNativeUA.enable_notification();
ReactNativeUA.handle_background_notification();
ReactNativeUA.set_named_user_id('user_id');
}
componentWillMount() {
// add handler to handle all incoming notifications
ReactNativeUA.on_notification((notification) => {
console.log('notification:', notification.data,
notification.url,
notification.platform);
alert(notification.alert);
});
}
render () {
return (<View><Text>ReactNativeUA</Text></View>);
}
}
React Native UA: https://github.com/globocom/react-native-ua
rnconfig
urbanairship
RN Networking: https://facebook.github.io/react-native/docs/network.html
Também suporta:
1. XMLHttpRequest (axios)
2. WebSocket
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.then((movies) => {
console.log('movies', movies);
})
.catch((error) => {
console.error(error);
});
rnconfig
fetch
RN Code Push: https://github.com/Microsoft/react-native-code-push
npm install -g code-push-cli
code-push register
code-push app add <appName>
code-push release-react <appName> <platform>
rnconfig
codepush
• RN Fabric: https://github.com/corymsmith/react-
native-fabric
• https://fabric.io/
1. Crashlytics
2. Beta
rnconfig
fabric
rnconfig
crashlytics
rnconfig
beta
• Depender de projetos open source experimentais
• Erros que a sua especialidade não está acostumada
• Atualizações constantes e quebras de contrato
• Ler muito código e estudar muito (relativamente pouca
documentação)
• Ter que criar bridges para módulos que já existem
reactnative
desvantagens
facebook.github.io
/react-native
reactnative
showcase
• Avalie sempre todas as alternativas.
Não existe bala de prata!
• Versão 0.35 (última, mas lançam uma nova numa média de
2 semanas)
• A próxima virá com uma contribuição nossa PR (#9617)
• Muitas apps estão nascendo com React Native
conclusão
• guibruzzi@gmail.com
• fb.com/guilhermehbruzzi
• github.com/guilhermebruzzi
• dev.globo.com (blog da globo.com)
• fb.com/globodev
• slideshare.net/guilhermebruzzi/react-native-na-globocom
contato
Perguntas?
Muitoobrigado!
=)

React Native na globo.com

  • 1.
  • 2.
  • 3.
    ambienteda globo.com • Grandes portaiscom mais de 50 milhões de acessos diários • Muitos programadores web que adoram JS e mais recentemente React • Nós amamos open source! opensource.globo.com
  • 4.
  • 5.
    oproblemadasapps dagcom • Problema atual:Todas em webview • One app to rule them all
  • 6.
    392 × 690392× 690 oproblemadasapps dagcom
  • 7.
    oproblemadasapps dagcom • Primeira Appem RN: Techtudo (depois g1, gshow e ge) • Um feed nativo para consumir matérias
  • 8.
    appshíbridas • Soluções Webviewcomo Cordova / Phonegap / ionic • Reaproveitamento de código forte • Problemas da Webview • “Cross-browser"
  • 9.
    códigonativo • Objective-C /Swift para iOS • Java para Android • Perfomance otimizada • 2 códigos para as mesmas regras de negócio
  • 10.
    pocnativo • 1 semanapara iOS • 1 semana para Android
  • 11.
    xamarin • C# comMono .NET framework e IDE própria • Compilado para interagir com o Java e Obj-C • Reaproveitamento de código
  • 12.
    react • Lib criadaem 2013 pelo Facebook • Performance na escrita de mudanças • Componentização por padrão • Comunidade ativa e open source
  • 13.
    exemploreact • Criado comcreate-react-app 1. Estilo inline 2. Props 3. State npm install -g create-react-app create-react-app my-app
  • 14.
  • 15.
    reactplataformas • “learn once,write everywhere”: 1. Android (suporte Padrão) 2. iOS (suporte Padrão) 3. Windows: https://github.com/ReactWindows/ react-native-windows 4. Ubuntu: https://github.com/CanonicalLtd/ react-native
  • 16.
    reactnative • Criado em2015 • JS e React • Estilo via dialeto de CSS / Flexbox • Performance nativa • Não usa webview • Reaproveitamento de código cross-plataforma
  • 17.
    pocreactnative • 2 semanaspara os dois (código único) Muitoobrigado! =)
  • 18.
    reactnative arquitetura • nenhuma webview •Thread JS (webkit) • Shadow Queue • Main e threads Nativa (inclui UI) • Mais profundamente em: https://www.youtube.com/ watch?v=Ah2qNbI40vE (Tadeu Zagallo)
  • 19.
  • 20.
    • Códigos: https://github.com/guilhermebruzzi/rnExamples •Exemplo geral 1. Hello World + Reload e hot reload 2. Componentes padrões: Textos, imagens e ListView 3. Routers que usamos reactnative exemplos
  • 21.
    • Linter (Eslintairbnb) • Flow (vs typescript) • Mobx (vs Redux) • RN Router Flux/ Mobx Router • Webview Bridge • Urban Airship • ES6 fetch • Code Push • Fabric reactnativeconfig nagcom
  • 22.
    rnconfig rnrouterflux/mobxrouter • React Nativerouter flux: https://github.com/aksonov/react-native-router-flux • React Native mobx: https://github.com/aksonov/react-native-mobx
  • 23.
    rnconfig linter • Linter (Eslintextendendo eslint-config-airbnb) • Erros na hora
  • 24.
    Tipagem no meiodo javascript // @flow const foo = (b: boolean): string => ( (b) ? 'Hello' : 'World' ); const bar: string = foo(); rnconfig flow
  • 25.
    const { action,observable } = mobx; const { observer } = mobxReact; class CountStore { @observable count = 0; @action addCount() { this.count++; } @action decCount() { this.count--; } } const store = new CountStore(); @observer class App extends React.Component { render() { return ( <div> <span>Contador: {store.count}</span> <button onClick={() => store.addCount()}> + </button> <button onClick={() => store.decCount()}> - </button> </div> ); } } ReactDOM.render(<App />, document.getElementById('app')); rnconfig mobx Controle de estado global (https://jsbin.com/qizehep)
  • 26.
    const injectScript =` WebViewBridge.onMessage = function (message) { console.log('Received from react native', message); }; WebViewBridge.send('hello from webview'); `; class App extends React.Component { onBridgeMessage(message) { const { webviewbridge } = this.refs; console.log('Received from webview', message); webviewbridge.sendToBridge("hello from react-native"); } render() { return ( <WebViewBridge ref="webviewbridge" onBridgeMessage={this.onBridgeMessage.bind(this)} injectedJavaScript={injectScript} source={{uri: "http://google.com"}}/> ); } } rnconfig webviewbridge React Native Webview Bridge: https://github.com/alinz/react-native-webview-bridge
  • 27.
    import ReactNativeUA from'react-native-ua'; class App extends Component { constructor(props) { super(props); ReactNativeUA.enable_notification(); ReactNativeUA.handle_background_notification(); ReactNativeUA.set_named_user_id('user_id'); } componentWillMount() { // add handler to handle all incoming notifications ReactNativeUA.on_notification((notification) => { console.log('notification:', notification.data, notification.url, notification.platform); alert(notification.alert); }); } render () { return (<View><Text>ReactNativeUA</Text></View>); } } React Native UA: https://github.com/globocom/react-native-ua rnconfig urbanairship
  • 28.
    RN Networking: https://facebook.github.io/react-native/docs/network.html Tambémsuporta: 1. XMLHttpRequest (axios) 2. WebSocket fetch('https://facebook.github.io/react-native/movies.json') .then((response) => response.json()) .then((responseJson) => { return responseJson.movies; }) .then((movies) => { console.log('movies', movies); }) .catch((error) => { console.error(error); }); rnconfig fetch
  • 29.
    RN Code Push:https://github.com/Microsoft/react-native-code-push npm install -g code-push-cli code-push register code-push app add <appName> code-push release-react <appName> <platform> rnconfig codepush
  • 30.
    • RN Fabric:https://github.com/corymsmith/react- native-fabric • https://fabric.io/ 1. Crashlytics 2. Beta rnconfig fabric
  • 31.
  • 32.
  • 33.
    • Depender deprojetos open source experimentais • Erros que a sua especialidade não está acostumada • Atualizações constantes e quebras de contrato • Ler muito código e estudar muito (relativamente pouca documentação) • Ter que criar bridges para módulos que já existem reactnative desvantagens
  • 34.
  • 35.
    • Avalie sempretodas as alternativas. Não existe bala de prata! • Versão 0.35 (última, mas lançam uma nova numa média de 2 semanas) • A próxima virá com uma contribuição nossa PR (#9617) • Muitas apps estão nascendo com React Native conclusão
  • 36.
    • guibruzzi@gmail.com • fb.com/guilhermehbruzzi •github.com/guilhermebruzzi • dev.globo.com (blog da globo.com) • fb.com/globodev • slideshare.net/guilhermebruzzi/react-native-na-globocom contato
  • 37.
  • 38.