document onclick with React

I got somthing like this on React?

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

Or is mandatory to use onClick on all components?

Upvotes: 0

Views: 1323

Answers (2)

mohammed sadik vk
mohammed sadik vk

Reputation: 50

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;

Upvotes: -1

Ehsan Samavati
Ehsan Samavati

Reputation: 99

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

Upvotes: 2

Related Questions