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?

1 Answer 1

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>
    );
  }
});

Sign up to request clarification or add additional context in comments.

3 Comments

wanted to avoid jquery, sorry I should have said that. I ended up with using html();
This is bit magical, apparently jquery does more than just const div = document.createElement('div'); div.innerHTML = '<script/>'; document.getElementById('put_script_here').appendChild(div);, but it works
Note that if the external scripts do document.write, you have another problem: stackoverflow.com/a/2360112/6962

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.