Skip to content
Advertisement

React: Perform action, only once, when html element is clicked

In jQuery, it’s pretty trivial to perform an action, only once, when an event is triggered on the html element.

For example:

$(".dropdown-trigger").on("click", function(event) {
  var self = this;
  $("html").one("click", function() {
    $(self).parents(".dropdown").removeClass("active");
  });
  $(this).parents(".dropdown").toggleClass("active");

  event.stopPropagation();
});

In React, it’s not so easy.

How can I perform an action, in React, when the html element is clicked, and perform that action only once (similar to my jQuery code)?

Advertisement

Answer

Using refs. Not very beatiful but at least it works. This requires React >16.8

import React, { useEffect, useRef } from 'react'

const App = () => {
  const ref = useRef()

  // Wait for DOM to load
  useEffect(() => ref.addEventListener('click', () => alert('Hi'), { once: true })

  return <button ref={ref}>Click on me (once)</button>
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement