Skip to content

Instantly share code, notes, and snippets.

@mtt87
Created March 5, 2019 01:16
Show Gist options
  • Save mtt87/9f2a920b213d40a2cc57d827d2f28ec5 to your computer and use it in GitHub Desktop.
Save mtt87/9f2a920b213d40a2cc57d827d2f28ec5 to your computer and use it in GitHub Desktop.
Fetch dynamically a component and render it at runtime on React Native
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
// This DOES NOT work (require is undefined)
import React from 'react';
import { View, Text } from 'react-native';
const Component = () => (
<View>
<Text>Hello world</Text>
</View>
);
export default Component
var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports,"__esModule",{value:true});
exports.default=void 0;
var _react=_interopRequireDefault(require("react"));
var _reactNative=require("react-native");
var _jsxFileName="/Users/mattia/Dev/component/index.js";
var Component=function Component(){return _react.default.createElement(_reactNative.View,{__source:{fileName:_jsxFileName,lineNumber:5}},_react.default.createElement(Text,{__source:{fileName:_jsxFileName,lineNumber:6}},"Hello world"));};
var _default=Component;
exports.default=_default;
// This WORKS
export default function(
React,
ReactNative,
) {
const { View, Text } = ReactNative;
const Component = () => (
<View>
<Text>Hello world</Text>
</View>
);
return Component;
};
Object.defineProperty(exports,"__esModule",{value:true});
exports.default=_default;
var _jsxFileName="/Users/mattia/Dev/component/index.js";
function _default(React,ReactNative){
var View=ReactNative.View,Text=ReactNative.Text;
var Component=function Component(){return React.createElement(View,{__source:{fileName:_jsxFileName,lineNumber:7}},React.createElement(Text,{__source:{fileName:_jsxFileName,lineNumber:8}},"Hello world"));};
return Component;
};
import React from 'react';
import ReactNative, { ActivityIndicator } from 'react-native';
class Loader extends React.Component {
state = {
loading: true,
Component: null,
};
async componentDidMount() {
try {
const res = await fetch('https://file-kiqtmevbgz.now.sh/');
const js = await res.text();
const factory = eval(js);
// passing down React and ReactNative is the only way it works
const Component = factory(React, ReactNative);
this.setState({ Component, loading: false });
} catch (err) {
console.error(err);
}
}
render() {
const { loading, Component } = this.state;
if (loading) {
return <ActivityIndicator color="#333" />;
}
return <Component />;
}
}
export default Loader;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment