How to use Platform Specific Packages in React Native and React Native for Web
As a React Native developer in 2021, I assume React Native for Web is part of the product. Still, many older React Native packages don’t support this. While this might seem like an obstacle at first, you can utilize platform-incompatible packages in React Native with a simple and straightforward solution. In this example, I’m going to use react-native-blur package, which is incompatible with React Native for Web.
The first clue of incompatibility is usually that the app isn’t working anymore, but by investigating the package’s source code, you can see if this is because there are platform incompatibilities. To do this, look to see if there are at the platform specific extensions in the source code. In the sourcecode for react-native-blur
, there are .ios.js
and .android.js
files in the source code but no .web.js
or default files.
Similarly, to use these packages, we need to make two components with platform specific extensions, one with the .native
extension and one with the .web
extension. In the native file, import and use the component from the incompatible package. In the web file, make a component with a similar compatible implementation.
In the parent component, import the file without the platform specific file extension, i.e. import BlurView from ‘./BlurView’
. This will allow the web app to build without looking for the incompatible package, allowing us to use it in one platform and not another.
Below is the full component where the platform-specific code is used.
The complete code sample for this article can be seen on GitHub here.