Search code examples
javascriptreactjsi18nextreact-i18next

How to retrieve ref from hoc translated component by i18next


I use i18next to translate my components in separate repo. Now I need to use method from one component in my main project. This is example component:

class ExampleComponent extends React.Component {
  constructor(props) {
    this.state = {
      text: '',
    };
    this.resetText = this.resetText.bind(this);
  }

  resetText() {
    this.setState({
    text: '',
    });
  }

  render() {
    <div/>
  }

export default translate('components', { withRef: true })(ExampleComponent);

And now I need to use resetText in my main project, without translations it works fine

class MainComponent extends Component {

  resetComponent() {
    return () => this.exampleComponent.resetText();
  }

  renderExampleComponent() {
    return (
      <ExampleComponent
        ref={(exampleComponent) => { this.exampleComponent = exampleComponent; }}
      />
    );
  }

  render() {
    return (
      <div>
        {this.resetComponent()}
      </div>
    );
  }

I tried this.refs.exampleComponent.resetText(); but it not works. In i18next documentation I found "withRef | store a ref to the wrapped component and access it by decoratedComponent.getWrappedInstance();" but where should I use this getWrappedInstance() to make it works? Someone have experience with this?

Greetings


Solution

  • I think with the provided code, your ref returns a wrapper, so you need to call getWrappedInstance on it: this.refs.exampleComponent.getWrappedInstance().resetText();