Breno Teixeira
Breno Teixeira

Reputation: 21

Embed react component into website without Iframes

my company wants to create a react component which is going to render a google maps frame, a search field and a result list. Basically to search, see results and see them on the map.

Today the component is created but we're using a lot different libs like react-router, react-redux, axios, etc.

We want to find out a way to embed our component to another websites in a simple way without using iframes(if possible). Ideally a solution where we could just ask for our clients to add a div with a specific id and our script tab.

Any ideas how to solve it?

Thank so much.

Upvotes: 2

Views: 2272

Answers (2)

Ray Luxembourg
Ray Luxembourg

Reputation: 196

The consumer needs to tag an HTML element with an identifier in this case a class name representing a certain type of widget.

<div class="ray_widget"></div>

Then in the root of our react application src/index.tsx or jsx We find all elements that are tagged and render react applications on it.

const WidgetDivs = document.querySelectorAll('.ray_widget')

WidgetDivs.forEach(divElement => {
  const root = ReactDOM.createRoot(divElement);
  root.render(
    <React.StrictMode>
      <Widget divElement={divElement}  />
    </React.StrictMode>
  );
})

You then bundle your application and the customer needs to include the script on their website

<script src="https://your-react-app-bundle-cdn/index.js" type="text/javascript"></script>

Resource: Embed React application without an iframe full post

Upvotes: 0

Dillan Wilding
Dillan Wilding

Reputation: 1111

In this situation, I'd suggest having Webpack bundle your component with whatever dependencies you need into a standalone js file. Then rather than using a typical app.js or index.js file that attaches an app to a body or div tag like create-react-app does, specifically use ReactDOM to render your component to a specific div based on ID. That way they just include your file and make sure they have the div with the ID and it'll take care of the rest. I've done something similar at a couple different jobs.

import ReactDOM from 'react-dom';
import MyComponent from 'my-component.js';
ReactDOM.render(<MyComponent />, '#my-div');

Besides that it's just tinkering with Webpack.

Upvotes: 2

Related Questions