How to convert this jQuery to function component or class component or react hooks

Viewed 10

How to convert this jQuery to function component or class component or react hooks

$(document).ready( function(){
    setTimeout(function(){
        if($('#DIV_ID').children().length === 0) {
            grecaptcha.render('DIV_ID', {
                'sitekey' : 'YOUR_SITE_KEY', 
                'callback' : recaptchaCallback
            });
        }
    }, 500);
});
1 Answers

You can use a ref to reference the element and register the 500ms delay in an on-mount effect hook

const recaptchaCallback = (token) => {
  // whatever
};

const Captcha = () => {
  const divRef = useRef(null);

  useEffect(() => {
    const timer = setTimeout(() => {
      grecaptcha.render(divRef.current, {
        sitekey: "YOUR_SITE_KEY",
        callback: recaptchaCallback,
      });
    }, 500);

    return () => {
      clearTimeout(timer);
    };
  }, []);

  return <div ref={divRef}></div>;
};
Related