Mosaic + React

Mosaic is great in conjunction with React! Learn to use it in this guide.

Before we start

This tutorial will guide you through the first steps of using Mosaic in conjunction with React.

If something goes wrong and you are blocked somewhere - feel welcome to check out the result of this tutorial, we uploaded it to GitHub for you 👍🏻

Create a project

First of all, let's create a simple React project. We are going to use the most common way to do that. See the command below!

npx create-react-app mosaic-101

Now let's run the project to make sure we see the same thing.

Install Mosaic

First of all, we are going to install the scripts package and the mosaic itself.

yarn add @tilework/mosaic-cra-scripts @tilework/mosaic

Then, we replace the react-scripts with the cra-scripts, which come from the @tilework/mosaic-cra-scripts package.

package.json
{
    "scripts": {
        "start": "cra-scripts start",
        "build": "cra-scripts build",
        "link": "cra-scripts link",
        "test": "cra-scripts test"
    }
}

Launch the project

When you launch the project after the modifications above, you should receive the same result as in the first launch - unchanged.

Prepare source code

In order to use the plugin system and create some plugins for the existing logic, we should put some namespaces into the source code. Let's start with modifying the App component and putting a namespace on that!

src/App.js
/** @namespace App/App */
function App() {
    ...

Create an extension

Local extensions, conventionally, are stored in a packages directory in the project root. So let's create this directory and initialize an npm module within it!

.
├── 📁 packages/
   └── 📁 sample-extension/
       └── 📄 package.json
├── 📁 src/
   ├── ...
   └── 📄 App.js
└── 📄 package.json

Install and enable the extension

First, we need to install the extension. For the local extensions, we need to add it to the dependencies block manually, as follows. Also, we add the postinstall and postupdate scripts in order for the local package to be symlinked into node_modules directory on any interactions with the dependencies.

package.json
{
    "dependencies": {
        "sample-extension": "file:./packages/sample-extension"
    },
    "scripts": {
        "postinstall": "cra-scripts link",
        "postupdate": "cra-scripts link"
    }
}

In order to enable the extension, we should declare this in the package.json file of one of the enabled extensions or themes. For now, the only enabled Mosaic module in the application is our application, hence we are going to declare this in our main package.json file.

package.json
{
    "mosaic": {
        "extensions": {
            "sample-extension": true
        }
    }
}

Afterwards, run the dependency installation in your main package in order to trigger the postinstall script and link the extension.

yarn

Declare a plugin

Inside of the extension we created, let's declare a plugin to modify the App component. The name file which the plugin is located in should end with .plugin.js and the file itself should export a configuration object.

For now, let's keep the logic intact, but log a message about the plugin being functional.

packages/sample-extension/src/plugin/App.plugin.js
const plugin = (args, callback) => {
    console.log('The plugin works!');
    
    return callback(...args);
};

export default {
    'App/App': {
        function: plugin
    }
};

In order for the application to get the new plugin file, restart the application. It is very important! Then, you will see our message in the console on the main page!

Add an element to the page

Let's modify the previously created plugin declaration file in order to append an element to the page. And, let's remove the console.log, we don't need it anymore.

const plugin = (args, callback) => {
    return (
        <>
            {callback(...args)}
            <p>I bring the message from the plugin!</p>
        </>
    );
};

After declaring this, we are going to see our additional paragraph rendered on the page.

Refactor thinking about SRP

In order for the application to be properly extensible, the logic within it should be granular. Modifying React trees after creation is considered a bad practice, we are going to use a different approach.

We are going to refactor the App component, in order for some additional contents to be able to be added to it without any additional effort. To do that, we'll separate the part which renders header's items from the other logic, so that we can append items there, instead of appending items to the app component itself!

/** @namespace App/renderHeaderContents */
function renderHeaderContents() {
  return (
    <>
      <img src={logo} className="App-logo" alt="logo" />
      <p>
        Edit <code>src/App.js</code> and save to reload.
      </p>
      <a
        className="App-link"
        href="https://reactjs.org"
        target="_blank"
        rel="noopener noreferrer"
      >
        Learn React
      </a>
    </>
  )
}

/** @namespace App/App */
function App() {
  return (
    <div className="App">
      <header className="App-header">
        {renderHeaderContents()}
      </header>
    </div>
  );
}

After this, let's change the previously created plugin declaration file to add an item to the header, not below the App component.

export default {
    'App/renderHeaderContents': {
        function: plugin
    }
};

Enjoy the results

After all of the actions above are complete, you are going to see this result. The additional element will be appended right to the middle of the page!

Last updated