0

I got somthing like this on React?

 $(document).on("click", function (e) { ... }

Or is mandatory to use onClick on all components?

2
  • Are you getting error when running this code? Commented Aug 17, 2022 at 10:33
  • I don't see a reason to use jQuery with React. We can simply use onClick for things like this. Is there any reason for you to use jQuery here? Commented Aug 17, 2022 at 10:34

2 Answers 2

2

It is not a good practice and You should try and avoid jQuery in ReactJS, But:

You can have that, but in order to do that you need to add your code in the right life cycle hook for example, you can do this

import React from 'react';
import $ from 'jquery';

useEffect(() => {
    function onClickHanlder (e) { ... }
    $(document).on("click", onClickHanlder)

    // to prevent leak memory unsubscribe from event on unmount
    return () => {
        $(document).off("click")
    }
},[]);

In a class component you can add your code in componentDidMount

Sign up to request clarification or add additional context in comments.

Comments

-1
import React from 'react';
import { useEffect } from 'react';

const App = () => {  

  useEffect(() => {
    initCustomScripts();
 }, [])

 const initCustomScripts = () => {
  document.getElementById('custom-button').addEventListener('click', function(){
        //code here
        alert('custom-button clicked');
  })
}

 return (
    <div>
        <button id="custom-button">Custom button</button>
    </div>
);

  
}
export default App;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.