Render onclick attribute using response.js when calling renderComponentToStaticMarkup

Let's say I have a reaction component that will be displayed on the side of the static html server. Some elements will have the onsubmit and onclick attributes, which will not be processed, but should still call the javascript function. In this particular case, I would like to create the server side of the contact form, but the client will need to download recaptcha:

var contactForm = React.createClass({
  render: function() {
    var recaptcha_id = "recaptcha_div";
    return(
        <div className="contact pure-form">
          <h4 className="boxedTitle">Contact Form</h4>
          <form key="form" method="POST" action=".">
          <fieldset key="sender_email">
            <label>Email</label>
            <input name="sender_email" placeholder="Your Email" type="email" />
          </fieldset>
          <fieldset key="subject">
            <label>Subject</label>
            <input name="subject" placeholder="Subject" type="text" />
          </fieldset>
          <fieldset key="message">
            <label>Message</label>
            <textarea name="message" placeholder="Message"/>
          </fieldset>
          <fieldset key="humanity">
            <div id={recaptcha_id}></div>
            <input ref="captcha_btn" type="button" value="Show reCAPTCHA" onClick={"showRecaptcha('"+recaptcha_id+"');"}></input>
          </fieldset>
          <fieldset key="submit">
            <input type="submit" className="btn btn-primary" value="Send"/>
          </fieldset>
          </form>
        </div>
    )
  }
});

console.log(React.renderComponentToStaticMarkup(contatForm()))

But onClick is not displayed. I tried several other things that didn't work:

  • tried the onclick attribute, but not displayed
  • the supplied component DidMount, which manually sets the attribute in the DOM node, but this is not called when rendering static markup
+4
3

onClick . . onClick={window.showRecaptcha.bind(null, recaptcha_id)}.

renderComponentToStaticMarkup, . JavaScript ( <script>) - . <script> addEventListener, , .

JavaScript 5 . onclick .. html, eval, setTimeout/setInterval , , , . .

+2

. dangerouslySetInnerHTML

 <td dangerouslySetInnerHTML={{__html: `
    <button onClick="alert('hello')" >Detalii</button>
  `}} 
 />

, ,

+2

I have the same problem because I have JS inserted in the DOM after rendering the component. I solved this with some tips from the previous answers and came up with this:

wrapper_function(){
   //function i want in my onclick attribute
   window.myFunc();
}
render() {

   return(
      <img className="openbtn" onClick={this.wrapper_function.bind(this)} src="..."/>

Actually even simpler: just assign an onclick listener to the client side JS

0
source

Source: https://habr.com/ru/post/1546202/


All Articles