curiousguy
curiousguy

Reputation: 3262

Can we apply Reactjs and Jquery together on HTML DOM element

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.

Upvotes: 1

Views: 285

Answers (1)

dting
dting

Reputation: 39287

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>

Upvotes: 1

Related Questions