ComponentsExamples

React Integration Example

Load the embed script and render a component from a React component.

This component loads the embed script once, renders CredibleMind into a container, and closes the embed when it unmounts.

import { useEffect, useRef } from 'react'

const SCRIPT_SRC = 'https://widget.crediblemind.com/embed.js'

function loadEmbedScript() {
  if (window.CMEmbed) return Promise.resolve()
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = SCRIPT_SRC
    script.async = true
    script.onload = resolve
    script.onerror = reject
    document.body.appendChild(script)
  })
}

export default function CredibleMindEmbed() {
  const container = useRef(null)

  useEffect(() => {
    let embed

    loadEmbedScript().then(() => {
      if (!container.current) return
      embed = window.CMEmbed.PageComponent({
        client: 'YOUR_CLIENT_IDENTIFIER',
        env: 'demo',
        parent: window.location,
        type: 'bare',
        components: ['topics'],
        setIframeHeight: height => {
          container.current?.firstElementChild?.style.setProperty('height', (height || 200) + 'px')
        }
        // Add onRouteChange, onModalOpen and onScrollTo from the recommended setup.
      })
      embed.render(container.current)
    })

    return () => embed?.close()
  }, [])

  return <div ref={container} />
}

For onRouteChange, onModalOpen and onScrollTo, copy the handlers from the recommended setup. Every property is described in the Properties Glossary.

Playground

On this page