gkeenley
gkeenley

Reputation: 7358

How do you make this.forceUpdate() apply to entire app in React Native?

I have a React Native app in which I want to place a button that appears on every screen that the user can click to force a re-render (using this.forceUpdate()). On every screen I have a custom <Header> component at the top, and I want to put the re-render button in that header since it appears on every screen, and I'd therefore have to add the button only once.

So one of my screens would look like this:

export default class Screen1 extends Component {
  render() {
    return(
      <View>
        <Header>
        ...rest of screen...
      </View>
    )
  }
}

And Header looks like this

export default class Header extends Component {
  render(){
    return(
      <View>
        <TouchableOpacity
          onPress={() => this.forceUpdate()}
        />
      </View>
    )
  }
}

Clicking the <TouchableOpacity> in the Header causes the Header itself to update, but not the entire screen. I assume this.forceUpdate() applies only to the component in which the <TouchableOpacity> is defined. So my question is, is there any equivalent of this.forceUpdate() that I can call in my header that will force a re-render of the entire screen?

Thanks!

Upvotes: 0

Views: 2445

Answers (1)

MPN7
MPN7

Reputation: 1313

As @parohy suggested it's not the way to go.. at all.
But has a temporary hack you can pass this.forceUpdate() as props to the header.
would look like this:

 export default class Screen1 extends Component {
  render() {
    return(
      <View>
        <Header forceUpdate={this.forceUpdate}>
        ...rest of screen...
      </View>
    )
  }
}
export default class Header extends Component {
  render(){
    return(
      <View>
        <TouchableOpacity
          onPress={() => this.props.forceUpdate()}
        />
      </View>
    )
  }
}

Upvotes: 1

Related Questions