Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

43
Vistas
JavaScript not running when added with componentDidUpdate

I have two versions of a component that display a file using the Jsmol library. The first version works but will displays the file before getting user input. I want the Jsmol functions to run after getting user input so I put the functions inside componentDidUpdate. However, when I do this the Jsmol does not run at all. I am thinking it is to prevent cross-site scripting attacks.

This is the code for my componentDidMount (This runs the JavaScript in innerHTML):

componentDidMount() {
      const script = document.createElement("script");
      script.id = "display"
      script.type = 'text/JavaScript';
      script.innerHTML = "jmolInitialize('jmol-14.32.63/jsmol');\
                           jmolApplet(400, `load results.pdb`, 0);"
      this.instance.appendChild(script);
}
render() {
       return (
          <>
            <div id="display" ref={el => (this.instance = el)} />
          </>
       );
}

And this is another version of the code (This does not run the JS in innerHTML):

componentDidUpdate() {
      const script = document.getElementById("jsmol-script");
      script.innerHTML = "jmolApplet(400, `load results/1A6W.pdb`, 0);"
}

render() {
       return (
          <>
            <div id="display" ref={el => (this.instance = el)} >
               <script id="jsmol-script" type="JavaScript"></script>
            </div>
          </>
    );
}
7 months ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos