简体   繁体   中英

Reuse code between React.js and React Native applications

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

I initially coded the class that retrieves data from an API when I built the iOS app. Thus, I used the fetch method available in React Native.

Unfortunately, there isn't such a method in React.js. My best option if I want to reuse my code is to abstract the call of the React Native's fetch method by creating a class HTTPRequests with a method fetch which will call the React Native's fetch method or the '$.get' method depending on the lib used by the project: React.js or React Native.

My question is the following: How can I detect the using of React.js or React Native in my project. My first idea is to detect if my JS code is executed through RCTRootView engine or a browser. But I've no idea how to accomplish this.

Any suggestion?

Thanks!

My suggestion would be to move shared logic into separate module (bower, npm, ES6), generalize the way you request data through fetch polyfill, and never ever bother with detecting React/React.native in your project. JS code detection will make your code unnecessary complicated and hard to support when new versions of React/React.native will come up.

I have successful experience of building a cross-platform application with React and React Native using the platform-specific extensions feature of React Native. I've just described how I structured the code in order to achieve that in a blog post Code sharing between React and React Native applications

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM