5

My app displays some Texts. I need to re-render a Component when the font size changes via Settings --> Accessibility --> Font size:

enter image description here

So basically this is se sequence:

  • The app is opened (foreground).
  • The user opens the Phone Settings so the app goes to foreground (not completely closed).
  • The user changes the Font size via via Settings --> Accessibility --> Font size.
  • The user closes the Settings and opens the app goes to foreground again.

At this point I need to reload the app because some Components need to be adapted.

I'm using react-native-device-info to get the font size using const fontScale = DeviceInfo.getFontScale(); but its value doesn't get updated until the app is completely closed and opened.

Any ideas?

Ale
  • 2,282
  • 5
  • 38
  • 67

1 Answers1

5

You can set the appstate to nextAppState. It should cause the component to rerender.

import React, {Component} from 'react';
import {AppState, Text} from 'react-native';

class AppStateExample extends Component {
  state = {
    appState: AppState.currentState,
  };

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!');
    }
    this.setState({appState: nextAppState});
  };

  render() {
    return <Text>Current state is: {this.state.appState}</Text>;
  }
}
Shivam
  • 3,091
  • 4
  • 30
  • 45
  • 1
    Thanks for your answer! Would it be possible to implementing using hooks? I'm quite new on React and my project uses hooks – Ale Apr 04 '19 at 16:12
  • I havn't dived much deeper into hooks, but only takes few mins of research to convert such a simple component into a functional component using `hooks`. What I currently use is `recomposeJS` – Shivam Apr 04 '19 at 16:19
  • I always get the error "Cant perform a React state update on an unmounted component" whenever I use setState in the appStateChange event handler. Any idea why? – Rakib Aug 05 '19 at 23:32