Example: Embedding a Widget in React
This example demonstrates how you can embed a widget in a React application. The widget is injected into the application by dynamically creating a script element in the useEffect
hook.
(optional)Install react-helmet
which is a component to manage all of your changes to the document head. You can install it using the command:
npm install react-helmet
Then use it in your React component like so:
import React, { useEffect, useRef } from "react";
import { Helmet } from "react-helmet";
function MyComponent() {
const widgetRef = useRef(null);
useEffect(() => {
const script = document.createElement("script");
script.src = "https://widget.crediblemind.com/bundle.js";
script.async = true;
script.dataset.mountIn = ".my-widget";
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
return (
<div>
<Helmet>
<style>{`
.my-widget {
width: 100%;
max-width: 1100px;
margin: 80px auto;
display: flex;
justify-content: center;
border: 1px dashed rgba(0, 0, 0, 0.2);
padding: 5px;
position: relative;
}
.my-widget::before {
content: 'Example Widget';
position: absolute;
display: block;
top: -18px;
font-size: 11px;
color: rgba(0, 0, 0, 0.5);
}
`}</style>
</Helmet>
<div ref={widgetRef} className="my-widget" data-prop-name="cm-widget1" />
</div>
);
}
export default MyComponent;
In this example, useEffect
is used to add the widget script when the component mounts and remove it when the component unmounts. useRef
is used to create a reference to the widget container div, which can then be accessed in the useEffect
hook. react-helmet
is used to manage the styles of your widget inside the React component.
Note: Be sure to replace .my-widget
and cm-widget1
with the class and the unique name we provide respectively.