Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render onclick attribute using react.js when calling renderComponentToStaticMarkup

Let us say I have a react component that will render to static html server side. Certain elements will have onsubmit and onclick attributes that will not be handled by react but should still call a javascript function. In this particular case I would like to generate a contact form server side but the client will need to load up 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 rendered. I tried a few other things that did not work:

  • tried onclick attribute, not rendered
  • supplied componentDidMount which manually set the attribute on the DOM node, but this isn't called when rendering static markup
like image 240
zbyte Avatar asked Jun 26 '14 22:06

zbyte


People also ask

Can I use onClick in anchor tag React?

To set an onClick listener on a link in React: Set the onClick prop on the link. The function you pass to the prop will get called every time the link is clicked.

Can we use onClick in Div tag React?

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.


1 Answers

I've hit the same issue. My solution was to use dangerouslySetInnerHTML

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

Hope it helps,

like image 110
ieugen Avatar answered Nov 04 '22 01:11

ieugen