Home > Software engineering >  Detect click from an html element outside a React app and a react component
Detect click from an html element outside a React app and a react component

Time:10-27

I have an html page with:

  • html elements
  • some empty divs that will be replaced with react elements.

I would like to listen to a "click event" of an html element from a react component.

Here, i need to get inside the "react-component" an event that will be triggered when we click on the "click" element.

<div id="click">button in static html</div>
<div id="react-component"></div> -> replace by a react component

Is there a way to achieve that? Thanks

CodePudding user response:

onClick event handler on any html tag will work in react

CodePudding user response:

You can still write normal JS code in react. Just add a useEffect(..., []) hook and bind your buttons onClick using standard JS code in there.

Here is the documentation for the JS onclick event: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick

CodePudding user response:

If you want to listen any click event (click anywhere) you can just use a classic eventListener in a useEffect from your react component:

useEffect(() => {
    window.addEventListener('click', () => { you function });

    return () => window.removeEventListener('click', () => { you function });
});

If what you want is to listen the click event of a given part of the app I would suggest you handle it from it's component and pass a callback to the one you want to handle the event.

CodePudding user response:

A few methods for this.
One of which is using querySelector or getElementById like you would in vanilla JS.

So you can do this:

// HTML:
<div id="click">button in static html</div>
<div id="react-component"></div> -> replace by a react component

// JSX:
const myElement = document.getElementById("click");
myElement.onclick = () => {
  ...
};
  • Related