How to make text appear/disappear using a switch

Hello everyone!

I am new to Expo and React Native in general so I have a question that may be really simple to answer.

Currently, the app I am working on displays accelerometer and geolocation data to the user constantly while the app is open. What I want the app to do is only display and update the accelerometer and geolocation data when a toggle switch is set to on and do not display and update otherwise.

This is what is currently in my render() method for the accelerometer and geolocation data:

  <Text style={styles.data}>
          Accelerometer:
          x = {this.state.accelerometerData.x.toFixed(2)}{', '}
          y = {this.state.accelerometerData.y.toFixed(2)}{', '}
          z = {this.state.accelerometerData.z.toFixed(2)}
        </Text>

        <Text style={styles.data}>
          Location: {this.state.locationResult}
        </Text>

And this is what I currently have for handling the toggle switch:

_handleToggleSwitch = () => this.setState(state => ({
    switchValue: !state.switchValue,
    tracking: !state.tracking
  }));

Thanks in advance!

Hey @ljeasson,

You can use conditional rendering to have the text only appear when tracking is enabled.

{ this.state.tracking &&
    /// Text components in here
}

Cheers,

Adam

1 Like

It now works as I want it to.

Thank you!

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.