Jean Lebrument
Jean Lebrument

Reputation: 5169

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!

Upvotes: 3

Views: 1568

Answers (2)

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4915

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

Upvotes: 2

Yevgen Safronov
Yevgen Safronov

Reputation: 4033

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.

Upvotes: 3

Related Questions