12

There are a bunch of answers on this, but I'm looking for something specific to reactjs

My component code:

  render: function () {

    return (
      <Modal {...this.props} title="Embed on your own site!">
        <div className="modal-body">
          <div className="tm-embed-container" dangerouslySetInnerHTML={{__html: embedCode}}>
          </div>
          <textarea className="tm-embed-code" rows="4" wrap="on" defaultValue={embedCode}></textarea>
        </div>
      </Modal>
    );
  }
});

The script tag is there on the page, but no execution. Should I go outside of react and just use good ol' DOM scripting as the other answers indicate?

Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
Kelly Milligan
  • 578
  • 1
  • 4
  • 17

1 Answers1

10

For what I understand, the react way would be to use the "componentDidMount" function to insert what you want in the the div, including some external script.

If your component is dynamic and receive regulary new props, you should also consider other methods (like componentDidUpdate).

More about script insertion with jQuery on this question

  componentDidMount: function(){
    var embedCode = this.props.embedCode; // <script>//my js script code</script>
    
    $('#scriptContainer').append(embedCode);
    },

  render: function () {
    return (
      <Modal {...this.props} title="Embed on your own site!">
        <div className="modal-body">
          <div className="tm-embed-container" id="scriptContainer">
          </div>
          <textarea className="tm-embed-code" rows="4" wrap="on" defaultValue={this.props.embedCode}></textarea>
        </div>
      </Modal>
    );
  }
});
Community
  • 1
  • 1
Bactisme
  • 1,644
  • 2
  • 15
  • 16
  • 2
    wanted to avoid jquery, sorry I should have said that. I ended up with using html(); – Kelly Milligan Mar 11 '15 at 18:14
  • 2
    This is bit magical, apparently jquery does more than just `const div = document.createElement('div');` `div.innerHTML = '';` `document.getElementById('put_script_here').appendChild(div);`, but it works – Sida Zhou Jan 17 '16 at 06:17
  • 1
    Note that if the external scripts do `document.write`, you have another problem: http://stackoverflow.com/a/2360112/6962 – Henrik N Jun 30 '16 at 14:33