Getting started
React Pluggable: A plugin system for JS & React apps
While React itself is a plugin system in a way, it focuses on the abstraction of the UI. It is inherently declarative which makes it intuitive for developers when building UI. With the help of React Pluggable, we can think of our app as a set of features instead of a set of components. It provides a mixed approach to solve this problem. We at GeekyAnts have used React Pluggable for large & complex apps like BuilderX to add independent and dependent features over time, and it has worked wonderfully for us.
Installation
Use npm or yarn to install react-pluggable
to your app.
# NPM
npm install react-pluggable --save
# Yarn
yarn add react-pluggable
We are using Typescript in all our examples. You can also use it with Javascript without types.
Basic Example
Let us create a plugin which will add an alert functionality to the component.
Create a ShowAlertPlugin and implement it with IPlugin interface.
ShowAlertPlugin.tsx
import { IPlugin, PluginStore } from "react-pluggable";
class ShowAlertPlugin implements IPlugin {
pluginStore!: PluginStore;
namespace = "ShowAlert";
getPluginName(): string {
return "ShowAlert@1.0.0";
}
getDependencies(): string[] {
return [];
}
init(pluginStore: PluginStore): void {
this.pluginStore = pluginStore;
}
activate(): void {
this.pluginStore.addFunction(`${this.namespace}.doIt`, () => {
alert("Hello from the ShowAlert Plugin");
});
}
deactivate(): void {
this.pluginStore.removeFunction(`${this.namespace}.doIt`);
}
}
export default ShowAlertPlugin;
Now, let's add ShowAlertPlugin to our app.
App.tsx
import React from "react";
import "./App.css";
import { createPluginStore, PluginProvider } from "react-pluggable";
import ShowAlertPlugin from "./plugins/ShowAlertPlugin";
import Example from "./components/Example";
const pluginStore = createPluginStore();
pluginStore.install(new ShowAlertPlugin());
function App() {
return (
<PluginProvider pluginStore={pluginStore}>
<Example />
</PluginProvider>
);
}
export default App;
Using that plugin in our Component.
Example.tsx
import * as React from "react";
import { usePluginStore } from "react-pluggable";
const Example = () => {
const pluginStore = usePluginStore();
return (
<>
<h1>Working</h1>
<button
onClick={() => {
pluginStore.executeFunction("ShowAlert.doIt");
}}
>
Show Alert
</button>
</>
);
};
export default Example;
ShowAlertPlugin will get injected into the component as shown: