Skip to content

Instantly share code, notes, and snippets.

@bkase
Last active December 1, 2017 23:04
Show Gist options
  • Save bkase/a32e8a48c5d9034c81a44551afea9c9e to your computer and use it in GitHub Desktop.
Save bkase/a32e8a48c5d9034c81a44551afea9c9e to your computer and use it in GitHub Desktop.
Reason React Native: Workaround to get jsThis from Reason-React
module Example {
type jsProps = {. x: int, y: string };
type state = ReasonReact.stateless;
type props = ReasonReact.noRetainedProps;
type action = ReasonReact.actionless;
let component = ReasonReact.statelessComponent("Example");
let make = (jsThis: Withjs.thisType) => (~x, ~y) => (_children) => {
/* ... */
let onPress = () => eventuallyCall_findNodeHandle(jsThis);
/* ... */
{
...component,
render: (_self) => {
<TouchableHighlight onPress=onPress>
<Text value="Hello world" />
</TouchableHighlight>
}
}
};
};
include Withjs.Make(Example);
type thisType = unit;
module type Component = {
type jsProps;
type state;
type props;
type action;
let component: ReasonReact.component(state, props, action);
let jsPropsToReason: (thisType) => ReasonReact.jsPropsToReason(jsProps, state, props, action);
};
module Make = (C : Component) => {
let _mutJsThis: ref(option(thisType)) = ref(None);
let injectThis = (this) => { _mutJsThis := Some(this); };
exception Not_wrapped;
let jsComponentFactory = () => switch _mutJsThis^ {
| None => raise(Not_wrapped)
| Some(jsThis) => ReasonReact.wrapReasonForJs(
~component=C.component,
C.jsPropsToReason(jsThis)
);
};
};
const withReason: ((any) => void, () => React.ComponentType<any>) => React.ComponentType<any> = (injectThis, componentFactory) => {
return class ReasonableComponent extends React.Component<any> {
Component: React.ComponentType<any>;
constructor(props) {
super(props);
injectThis(this);
this.Component = componentFactory();
}
render() {
const Component = this.Component;
return <Component {...this.props}/>;
}
}
}
//
// Usage: Use the HoC to use the Reason component from JS
//
import { jsComponentFactory, injectThis } from './lib/js/example.js'
export default withReason(injectThis, jsComponentFactory);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment