React Native Web on SPA

React Native Web and ui-shared on SPA #

After creating our ui-shared library we want to use it on our SPA application. For that we will need to install @mr/ui-shared and react-native-web for our spa web application:

yarn lerna add @mr/ui-shared --scope=@mr/spa
yarn lerna add react-native-web --scope=@mr/spa

Now, we need to update our packages/spa/index.js:

import "./index.css";

import { AppRegistry } from "react-native";
import App from "./App";

AppRegistry.registerComponent("App", () => App);
AppRegistry.runApplication("App", {
  rootTag: document.getElementById("root"),
});

Here, we are just following the instructions of react-native-web documentation here. We are using react-native to register our application to be able to use our react-native components with react-native-web.

It works out of the box because we are using create-react-app,which already do the alias of react-native to react-native-web. If I were doing all the configuration by hand for a react project I would have to do that configuration as well. react-native-web documentation contains web recipes for that, and we have here and here a good explanation about that.

Now we update packages/spa/App.js to use @mr/ui-shared:

import React from "react";
import "./App.css";

import { allBooks } from "@mr/utils";
import { BookCard } from "@mr/ui-shared";

function App() {
  return (
    <div>
      <h1 className="App">List of Books</h1>
      <ul>
        {allBooks().map(function renderBook(book) {
          return (
            <li key={book.id}>
              <BookCard book={book} />
            </li>
          );
        })}
      </ul>
    </div>
  );
}

export default App;

It should be working well. We can now remove dependency @mr/ui-web.

The interesting thing here is, we are still able to use react-dom components as we can see here, with h1 component.

Published