Skip to content

Commit

Permalink
turnstile component
Browse files Browse the repository at this point in the history
  • Loading branch information
cankurttekin committed Nov 12, 2024
1 parent b733d24 commit df4a348
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 16 deletions.
2 changes: 1 addition & 1 deletion frontend/src/components/Register.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ const Register = () => {
specialChar: false,
});
const [isPasswordFocused, setIsPasswordFocused] = useState(false); // Track if the password field is focused
const [turnstileToken, setTurnstileToken] = useState('');
const [turnstileToken, setTurnstileToken] = useState(null);
const navigate = useNavigate();

// Password validation function
Expand Down
43 changes: 28 additions & 15 deletions frontend/src/components/Turnstile.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,38 @@ import React, { useEffect } from 'react';

const Turnstile = ({ siteKey, onVerify }) => {
useEffect(() => {
// Load the Turnstile script only once
const script = document.createElement("script");
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
script.async = true;
document.body.appendChild(script);
// Check if Turnstile script is already loaded
if (!document.querySelector("script[src='https://challenges.cloudflare.com/turnstile/v0/api.js']")) {
const script = document.createElement("script");
script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
script.async = true;
script.defer = true;
document.body.appendChild(script);
}

// Initialize Turnstile widget after script loads
const onLoad = () => {
if (window.turnstile) {
window.turnstile.render('#turnstile-widget', {
sitekey: siteKey,
callback: onVerify,
});
}
};

// Check if script has already loaded
if (window.turnstile) {
onLoad();
} else {
window.addEventListener("load", onLoad);
}

return () => {
// Cleanup script when component unmounts
document.body.removeChild(script);
window.removeEventListener("load", onLoad);
};
}, []);
}, [siteKey, onVerify]);

return (
<div
className="cf-turnstile"
data-sitekey={siteKey}
data-callback={onVerify}
></div>
);
return <div id="turnstile-widget" className="cf-turnstile"></div>;
};

export default Turnstile;

0 comments on commit df4a348

Please sign in to comment.