skip to Main Content

I got somthing like this on React?

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

Or is mandatory to use onClick on all components?

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search