Share same code for web and mobile application part 2

In the previous blog we did the setup for monorepo and created a components lib to share components between react-native and next app now we will add Native-Base in our project and will see how we can use those components.

We will start by adding some dependencies so run the following commands in the workspace root. (Native-Base also requires react-native-web installation but we are not adding now as we added in the previous part.)

npm install native-base @expo/next-adapter
npm install next-transpile-modules --save-dev
expo install react-native-svg react-native-safe-area-context

Open react-native app App.tsx and wrap with NativeBaseProvider.

//apps/mobile-app/src/app/App.tsx

import React from 'react';
import { SafeAreaView, StatusBar } from 'react-native';
import { NativeBaseProvider } from 'native-base';
import { TextMessage } from '@twitter/shared-components';

const App = () => {
  return (
    <NativeBaseProvider>
      <StatusBar />
      <SafeAreaView>
        <TextMessage message="TextMessage In React-Native App" />
      </SafeAreaView>
    </NativeBaseProvider>
  );
};

export default App;

Open next app next.config.js and update the config as below

//apps/web-app/next.config.js

// eslint-disable-next-line @typescript-eslint/no-var-requires
const withNx = require('@nrwl/next/plugins/with-nx');
const { withExpo } = require('@expo/next-adapter');
const withTM = require('next-transpile-modules')([
  'react-native-web',
  'react-native-svg',
  'native-base',
]);
/**
 * @type {import('@nrwl/next/plugins/with-nx').WithNxOptions}
 **/
const nextConfig = {
  ....
  ...
  ..
  .
};

module.exports = withExpo(withTM(withNx(nextConfig)));

next open _app.tsx in the next app and wrap the <Component/> with NativeBaseProvider.

import { AppProps } from 'next/app';
import React from 'react';
import { NativeBaseProvider } from 'native-base';

function CustomApp({ Component, pageProps }: AppProps) {
  return (
    <NativeBaseProvider>
      <Component {...pageProps} />
    </NativeBaseProvider>
  );
}

export default CustomApp;

Open libs/shared-components/src/lib/text-message/text-message.tsx and we will replace <Text> from react-native to native-base.

import { Text } from 'native-base';

export interface TextMessageProps {
  message: string;
}

export function TextMessage(props: TextMessageProps) {
  return (
    <Text textAlign={'center'} fontSize={'2xl'} color={'red.300'}>
      {props.message}
    </Text>
  );
}

export default TextMessage;

Let's now run both apps.

Result

We explored how to set up native-base in monorepo setup for react-native and next apps and use native-base components in shared lib.