Iavor Orlyov
Iavor Orlyov

Reputation: 562

Using react component in a different application

What I'm trying to achieve is:

  1. Building simple react app - the template is create react app
  2. Copying output file (main.*.js)
  3. Pasting it in another react app
  4. Importing render function to render the first app into the second one

Simple react app code:

interface Props {
  greeting: string;
}
export module AppModule {
  export const sendGreetings = ({ greeting }: Props) => {
    return `Hello ${greeting}`;
  };
}

Builder file code:

!function(){"use strict";var n;(n||(n={})).sendGreetings=function(n){var e=n.greeting;return"Hello ".concat(e)}}();

Trying to import this file into another app I get this error:

File 'c:/vscode/test-react-app/test-sc-react/src/main.783e0281.js' is not a module.ts(2306)

Which is obvious. I changed the output file manually to:

export function initApp(){"use strict";var n;(n||(n={})).sendGreetings=function(n){var e=n.greeting;return"Hello ".concat(e)}};

It works but the only function that I'm able to access is initApp but not sendGreetings

I've been struggling with this for a while now and I would really appreciate any helpful suggestions

Upvotes: 2

Views: 1293

Answers (3)

sultan
sultan

Reputation: 4739

🎯 Solution #1

You can use an iframe to inject your react app:

<iframe src='path-to-your-app.html'/>

🎯 Solution #2

Go with micro-frontend architecture approach. Where a front-end app is decomposed into individual, semi-independent "microapps" working loosely together.

As a starting point, you can try npx create-mf-app instead of the CRA.

Upvotes: 2

Rohit Khandelwal
Rohit Khandelwal

Reputation: 632

You can include your js code directly on run time. You can use window.addEventListener to load js/css incoming from an outside source. You just have to append that js to your document on the load event.

Upvotes: 0

Sparko Sol
Sparko Sol

Reputation: 717

I used Bit.dev for my components that are used across multiple applications & there is an article regarding your issue

https://blog.bitsrc.io/sharing-react-components-across-multiple-applications-a407b5a15186

I think it would help.

Upvotes: 0

Related Questions