Home > Mobile >  document onclick with React
document onclick with React

Time:08-17

I got somthing like this on React?

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

Or is mandatory to use onClick on all components?

CodePudding user response:

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

CodePudding user response:

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;
  • Related