0

Though this is not the best approach to the problem, I do need my React app to interact with jQuery till I come up with a better solution.

In the HTML page for my entry point component, I have a simple jQuery listener -- see below:

<html>
... // Omitted for brevity
<body>
... // Omitted for brevity
<script type="text/javascript">

   $(".my-class").on("click", function() {
      debugger;
      // We'll do something here
   })

</script>
</body>
</html>

Then, in my dumb component, I have the following but it's not working. When I click my button, I'm not hitting the break point I set in the listener.

const MyComponent = () => {
   return(
      <div>
         <a href="#" className="btn-primary my-class">Click Me!</a>
      </div>
   );
}

export default MyComponent;

Any idea how I can get this to work?

Sam
  • 26,817
  • 58
  • 206
  • 383
  • Why do you want to use `jQuery`, instead you can use `onClick` event binding to your component or `a` itself. Then why jQuery click binding? – Abin Thaha Sep 10 '18 at 06:02
  • Trying to use a third party jQuery plug-in. When I have more time, I'll look for an alternative so that I can handle everything in React and not mix these two technologies. In the meantime, I do need the functionality the plugin provides. – Sam Sep 10 '18 at 06:04

1 Answers1

2

Add your method inside ready handler:

jQuery(function($) {
  // your code here
});

Also, you may call the jQuery method in the componentDidMount hook:

componentDidMount() {
  // your jQuery code here
}

If you don't want to hook your jquery method in the component itself and just use in the html, then you also need to inject the React and the ReactDom in your file:

// index.js
import { React } from 'react'
import { ReactDom } from 'react-dom'
import { $ } from 'jQuery'

// index.html
<script src="index.js"></script>
<!-- your jquery hook -->
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231