Emily
Emily

Reputation: 141

Conditional component rendering react native

Im trying to render conditional component. I have MapView with the location, what i want to achieve is: If the location is granted from the user or the location can not be found, instead of MapView I want to render a Textinput where users can type their location manually. This is my code

export default class GpsLocation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: null,
    };
    this._getLocationAsync();
  }

  _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    let location = await Location.getCurrentPositionAsync({
      enableHighAccuracy: true,
    });

    let region = {
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      latitudeDelta: 0.0045,
      longitudeDelta: 0.0045,
    };
    this.setState({ region: region });
  };

  render() {
    if (this.status === "granted") {
      return (
        <View style={styles.locationContainer}>
        <Text style={styles.note}>Adresa</Text>
        <MapView
          initialRegion={this.state.region}
          showUserLocation={true}
          showCompass={true}
          rotateEnabled={false}
          style={{ flex: 1, borderRadius: 10 }}
        ></MapView>
      </View>
      );
    } else {
      return (
        <TextInput/>
      );
    }
  }
}

Upvotes: 0

Views: 70

Answers (1)

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this way

constructor(props) {
    super(props);
    this.state = {
      region: null,
      status : undefined, // add initially `undefined`
    };
    this._getLocationAsync();
  }

_getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    .......
    this.setState({ ... , status }); // update status here
  };

render() {
  // change here also
  return this.state.status === "granted" ? (
        <View style={styles.locationContainer}>
          <Text style={styles.note}>Adresa</Text>
          <MapView
            initialRegion={this.state.region}
            showUserLocation={true}
            showCompass={true}
            rotateEnabled={false}
            style={{ flex: 1, borderRadius: 10 }}
          ></MapView>
      </View>
      ) : <TextInput/> ;       
  }

Upvotes: 2

Related Questions