Reusable code between React.js and React Native activities

I want to reuse code that retrieves data from an API for two apps. One of them is an iOS app using React Native. The other is a website using React.js.

I originally coded a class that fetches data from an API when building an iOS app. So I used the method fetch

available in React Native.

Unfortunately, there is no such method in React.js. My best option, if I want to reuse my code, is to abstract away the React Native method call by fetch

creating a class HTTPRequests

with a method fetch

that will call the React Native method fetch

or the $ .get 'parameter depending on the lib used by the project: React.js or React Native.

My question is this: how can I detect the use of React.js or React Native in my project. My first idea is to determine if my JS code is being executed through an engine RCTRootView

or a browser. But I don't know how to do it.

Any suggestion?

Thank!

+3


source to share


2 answers


My suggestion was to move the common logic into a separate module (bower, npm, ES6), generalize the way to query the data with a fetch polyfill, and never worry about React / React.native being detected in your project. JS code detection will make your code redundant and complex when new versions of React / React.native are released.



+3


source


I have a successful track record of building a cross-platform app with React and React Native using a React Native feature extension framework . I just described how I structured the code to achieve this in a blog post Sharing codes between React and React Native apps



0


source







All Articles