0

I have the following embed code I need to integrate into my React app (using hooks):

<script 
class="123abc" 
type="text/javascript" 
src="https://cdn2.fake.com/Scripts/embed-button.min.js" 
data-encoded="lsakjdfioejfklsdKLJFLDSidjfklJSDJfLFKJEI88DdfDF8Ad9sa7">
</script>

How would I go about doing this? The resources I've found don't seem to allow me to implement the data-encoded part...

Based on Adding script tag to React/JSX you can see the answer has a useEffect & hooks solution, but I can't figure out how I would implement the data-encoded part (or the class part for that matter).

realhat
  • 177
  • 1
  • 1
  • 9

3 Answers3

1

you can create a portal to add a script block instead of mutating the DOM directly from within your react script!

amdev
  • 6,703
  • 6
  • 42
  • 64
1

For editing the documents head usually you use react-helmet.

Supports all valid head tags: title, base, meta, link, script, noscript, and style tags.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • Thanks Dennis, however it's not the document head that I want to modify. I want to insert a embed button from a finance partner into a component within my react app so that the button renders. Would `react-helmet` accomplish that? – realhat Mar 29 '20 at 17:49
  • You add the script to documents head, yes react-helmet does that - read the docs – Dennis Vash Mar 29 '20 at 17:53
  • I've read the docs (which are very confusing), but am not having any success. I'm using Next.js for SSR, so maybe that's the issue. But clearly just importing `import { Helmet } from "react-helmet";` then doing `` doesn't work. – realhat Mar 29 '20 at 18:30
  • 1
    Next.js has it's own head management system, which is next/head, it's almost the same as react-helmet. – Dennis Vash Mar 29 '20 at 18:32
  • Okay, looking into that now! Thanks! – realhat Mar 29 '20 at 18:32
  • 1
    Consider just asking another question and upvoting answer which helped you. – Dennis Vash Mar 29 '20 at 18:33
  • Thanks Dennis, I've done so here: https://stackoverflow.com/questions/60919281/how-to-use-next-head-to-render-a-script – realhat Mar 29 '20 at 18:58
0

How about this:

componentDidMount () {
    const script = document.createElement("script");
    script.src = "https://cdn2.fake.com/Scripts/embed-button.min.js";
    script.async = true;

    document.body.appendChild(script);
}
Jon Jones
  • 1,014
  • 1
  • 9
  • 17
  • Thanks @jon-jones, but I'm using React Hooks (i.e., ComponentDidMount is not a thing). This is partially why I am stuck. See: https://stackoverflow.com/questions/34424845/adding-script-tag-to-react-jsx/34425083#34425083 where they used the code you provided, and then later updated it to use hooks. However, in the hook example, I don't know how I would access the data-encoded... – realhat Mar 29 '20 at 17:41