1

I am pretty new in ReactJS . I have created a DOM element using reactJS JSX

var Button = React.createClass({
    render: function() {
        return <div><button className="btn btn-primary" id="viewThis"> View This</button></div>
    },          
});

Now I want to apply some jquery stuffs on that element based on some event for eg :

$("#viewThis").click(function()  {
   //Code goes here
}) 

If this is doable. For some reason my jquery code is not working.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
curiousguy
  • 3,212
  • 8
  • 39
  • 71

1 Answers1

1

This is because you are trying to bind a click handler to a dynamically generated element. While you can get around this:

Click event doesn't work on dynamically generated elements

const App = () => (
  <div>
    <button className="btn btn-primary" id="viewThis"> View This</button>
  </div>
);

ReactDOM.render(<App />, document.getElementById('app'));

$('#app').on('click', '#viewThis', () => console.log('clicked'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

You probably just want to use onClick in the component:

const App = () => (
  <div>
    <button className="btn btn-primary" onClick={() =>console.log('clicked')}> View This</button>
  </div>
);

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Community
  • 1
  • 1
dting
  • 38,604
  • 10
  • 95
  • 114