1

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

1

4 Answers 4

1

onClick event handler on any html tag will work in react

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

Comments

1

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

Comments

1

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 = () => {
  ...
};

Comments

0

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.

1 Comment

This incorrectly removes the event listener. The object references of those two arrow functions are not equal, therefore the real click listener might not get removed. Also, don't forget to add a dependency array, otherwise the code runs on every render.

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.