Kit
Kit

Reputation: 359

Why forceUpdate doesn't work after click button?

I'm doing a little project using ag-agrid and I'm trying to translate it.

My objetive is when user click in a button it change the language and to change the language the page must be refreshed

when click on button:

changeLanguage(lang) {
    this.setState({language: lang},
    this.forceUpdate());
  }

the problem is:

forceUpdate() is not working

render and construtor:

constructor(props) {
    super(props);

    this.state ={
       language: 'pt'
    }

    this.changeLanguage = this.changeLanguage.bind(this);
}


render() {
  return (
<div className="ag-theme-balham" style={{ height: '700px', width: '95%' }}>

  <Row>
    <Button onClick={() => this.changeLanguage('pt')}> PT </Button>
    <Button onClick={() => this.changeLanguage('en')}> EN </Button>                
  </Row>

  <br/>

  <AgGridReact
     //props of grid
     localeText={this.state.language === 'pt' ? pt : en}

  />
</div>
);
}

I'm doing something wrong when I'm using forceUpdate?

codeSandBox

Note: pt and en are data from a json file

Upvotes: 0

Views: 1664

Answers (1)

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38827

You can trigger a re-render by adding a key property in combination with this.state.language to the AgGridReact component instead of using this.forceUpdate(). This should cause a re-render when you change the language via the button clicks:

<AgGridReact
  key={this.state.language}
  ... other props
/>

Here is an example in action.

I don’t see any issues with your code, this seems like more of an issue with the grid component failing to update. You are updating state correctly.

Hopefully that helps!

Upvotes: 2

Related Questions