Search code examples
reactjsrecaptcha

react-recaptcha not update its language display when the sites change language


Edit:
I tried to follow below link to reset the recaptcha by recaptchaInstance.reset().
I added constructer(), ref={e => recaptchaInstance = e} on ,
recaptchaInstance.reset() on componentWillMount().

error shows

  TypeError: Cannot read property 'reset' of undefined

https://www.npmjs.com/package/react-recaptcha

Initial problems:
When I npm start the project, recaptcha shows correct langauge.

But when I change the language of the site using changeLanguage(),
the language of the recaptcha always show zh_tw.

I checked the the prop hl of recaptcha, when I am changing the language of my site, it shows the correct value for every changing.
I tried refresh the page, but recaptcha still showing incorrect langauge
It seems like the recaptcha do not rerender after the window.location.reload().

How can I solve this issue and make the recaptcha reset when window.location.reload() run?

login.jsx

import React from "react";
import Recaptcha from 'react-recaptcha'
...
let recaptchaInstance;

class Login extends Component {

   constructor() { //add after edit
     super();
     this.key = 0;
   }

    state = {
            ...
            recapchaLang: '',
    };


componentWillMount(){
   recaptchaInstance.reset(); //add after edit
   this.setState({
     recapchaLang: localStorage.getItem('currentLang') === 'en' ? 'en' : localStorage.getItem('currentLang') === 'tw'? 'zh-TW':localStorage.getItem('currentLang') === 'cn'?'zh-CN':''
   })
}

    ...
  render(){
         <Recaptcha
             key={this.key} //add after edit
             ref={e => (recaptchaInstance = e)} //add after edit
             sitekey={window.RECAPTCHA_KEY}
             render="explicit"               
             hl = {this.state.recapchaLang}
             verifyCallback = {() =>{this.setState({isVerifiedByRecaptcha:true,showRecaptchaAlert:false})}}
        />
  }
}

FirstPage.jsx

...
  class FirstPage extends Component {
      changeLanguage = (lang) => {
         localStorage.setItem("currentLang", lang);
         i18n.changeLanguage(lang);
         window.location.reload();
      };
      render() {
             ...
            <Login />
           <span onClick={() => this.changeLanguage("zh")}>TW</span>|
            <span onClick={() => this.changeLanguage("cn")}>CN</span>|
            <span onClick={() => this.changeLanguage("en")}>EN</span>
       }

}

Solution

  • Problem solved.
    I just change to use react-google-recaptcha instead of react-recaptcha.