masroorejaz / react-simple-captcha

A very simple and powerful captcha for ReactJS
40 stars 19 forks source link

[SOLUTION] How to get it working with Next.js #32

Closed ChrisCates closed 1 year ago

ChrisCates commented 1 year ago

For those looking for a way to get this working in Next.js or any SSR based environment. Do the following:

Step 1: Create a null reference to the library.

const [ReactCaptcha, setReactCaptcha] = useState(null as any)

Step 2: Dynamically load module using useLayoutEffect

useLayoutEffect(() => {
    async function loadModule() {
      setReactCaptcha(await import('react-simple-captcha'))
    }
    loadModule()
}, [])

Step 3: have a useState() hook for rendering the Captcha Component.

useLayoutEffect(() => {
    if (ReactCaptcha) {
      setRender(true)
    }
}, [ReactCaptcha])

useEffect(() => {
    if (render) {
      setTimeout(() => {
        ReactCaptcha.loadCaptchaEnginge(6, '#07090e', 'rgb(0, 200, 0)', 'lower')
      }, 250)
    }
}, [render])

Step 4: Render Captcha Component only when it's ready to be rendered.

return (
  <div>
    <div className="captcha">
      {render ? <ReactCaptcha.LoadCanvasTemplate /> : null}
    </div>
  </div>
)
masroorejaz commented 1 year ago

Thanks you so much for the solution @ChrisCates

I am referencing your solution in official Read Me of NPM.

Again Thank you so much.