Nemanja Srećković
Nemanja Srećković

Reputation: 359

how to force reload of react-recaptcha on state change (language update)

I want to reload reCaptcha widget on my state change, when I get new current_lang.

I used componentDidUpdate

componentDidUpdate() {
  if (this.recaptchaInstance) {
    this.recaptchaInstance.reset();
  }
}

which looks like it re-render component, but language stays the same?

this is my component

<Recaptcha
  ref={e => (this.recaptchaInstance = e)}
  sitekey="using_it_just_didnt_copy_it_here"
  size="normal"
  render="explicit"
  hl={language.current_lang}
  onloadCallback={this.onloadRecaptcha}
/>

Can someone please point me in right direction? Thanks!

Upvotes: 2

Views: 3843

Answers (2)

Chris
Chris

Reputation: 59531

Perhaps you need to re-mount Recaptcha rather than just re-rendering it. You should use the key prop to force a re-mount:

constructor() {
  super();
  this.key = 0;
}

componentDidUpdate() {
  if (this.recaptchaInstance) {
    this.key++; 
  }
}

<Recaptcha
  key={this.key}
  ref={e => (this.recaptchaInstance = e)}
  sitekey="using_it_just_didnt_copy_it_here"
  size="normal"
  render="explicit"
  hl={language.current_lang}
  onloadCallback={this.onloadRecaptcha}
/>

Upvotes: 6

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15851

componentDidUpdate used in this way will make the state of the application inconsistent and/or less predictable. I suggest that hl={language.current_lang} should be hl={state.current_lang}. Updating the state with a new language through setState() will make the view to render again with new values (updated language) and will keep state consistent, predictable and easily debbugable through (I.E.) react dev tools.

Upvotes: 0

Related Questions