Skip to content

Instantly share code, notes, and snippets.

@foxdonut
Created November 23, 2016 21:59
Show Gist options
  • Save foxdonut/f70f71a99d9e5f9000882e24f9eb4336 to your computer and use it in GitHub Desktop.
Save foxdonut/f70f71a99d9e5f9000882e24f9eb4336 to your computer and use it in GitHub Desktop.
Meiosis on React-Native
import React, { Component } from 'react';
import { AppRegistry, Button, StyleSheet, Text, View } from 'react-native';
import { createComponent, run } from "meiosis";
// This is from the React Native hello world example.
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
content: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
// This is from the Meiosis counter example, with RN components.
const view = (model, propose) => {
const onInc = () => propose({ add: 1 });
const onDec = () => propose({ add: -1});
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Meiosis on React Native
</Text>
<Text style={styles.content}>
Counter: {model.counter}
</Text>
<Button title="Increment" onPress={onInc}></Button>
<Button title="Decrement" onPress={onDec}></Button>
<Text style={styles.content}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
};
// This is standard Meiosis code.
const receive = (model, proposal) => ({ counter: model.counter + proposal.add });
const rootComponent = createComponent({ view, receive });
const initialModel = { counter: 0 };
// This code would be in a meiosis-react-native library and you would import MeiosisReactNative.
const MeiosisReactNative = () => {
const exported = {};
const hook = { rerender: () => null };
let root = null;
let initialModel = null;
exported.renderer = (model, component) => {
if (!root) {
root = component;
initialModel = model;
}
else {
hook.rerender(model);
}
};
class MeiosisReactNativeComponent extends Component {
componentWillMount() {
hook.rerender = data => this.setState(data);
if (initialModel) {
this.setState(initialModel);
}
}
render() {
if (root && this.state) {
return root(this.state);
}
return null;
}
}
exported.ReactNativeComponent = MeiosisReactNativeComponent;
return exported;
};
// This is how you would use MeiosisReactNative.
const { renderer, ReactNativeComponent } = MeiosisReactNative();
run({ renderer, initialModel, rootComponent })
AppRegistry.registerComponent('MeiosisNative', () => ReactNativeComponent);
@alexriva
Copy link

alexriva commented Apr 1, 2017

And what about nap function ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment