Adding script tag to React/JSX

后端 未结 17 1103
感动是毒
感动是毒 2020-11-22 03:52

I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:

\'use strict\';

import \'../../styles/         


        
17条回答
  •  时光取名叫无心
    2020-11-22 04:18

    Solution depends on scenario. Like in my case, I had to load a calendly embed inside a react component.

    Calendly looks for a div and reads from it's data-url attribute and loads an iframe inside the said div.

    It is all good when you first load the page: first, div with data-url is rendered. Then calendly script is added to body. Browser downloads and evaluates it and we all go home happy.

    Problem comes when you navigate away and then come back into the page. This time the script is still in body and browser doesn't re-download & re-evaluate it.

    Fix:

    1. On componentWillUnmount find and remove the script element. Then on re mount, repeat the above steps.
    2. Enter $.getScript. It is a nifty jquery helper that takes a script URI and a success callback. Once the script it loaded, it evaluates it and fires your success callback. All I have to do is in my componentDidMount $.getScript(url). My render method already has the calendly div. And it works smooth.

提交回复
热议问题