Home > OS >  Fade out loading screen in React Native
Fade out loading screen in React Native

Time:10-05

I've made a test weather app which has a loading screen with a timeout so it shows the Home screen after 6 sec (this will be replaced by the time the API-fetch is loading). Everything works fine however I'd like the loading screen to fade into the Home screen (now it just snaps right into it). Is there a way of doing this? Thanks

  export default function Home() {
    const [isLoading, setIsLoading] = useState(true)
    const [temperature, setTemperature] = useState(0)
    const [weatherCondition, setWeatherCondition] = useState(null)

const lat = 60
const lon = 24


useEffect(() => {
    setTimeout(() => {
                fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&APPID=${API_KEY}&units=metric`)
                .then(res => res.json())
                .then(json => {
                    setTemperature(json.main.temp)
                    setWeatherCondition(json.weather[0].main)
                    setIsLoading(false)
                })
                .catch((e) => console.log(e))
        }, 6000);

  },[]);


  return (
    <View style={styles.container}>

        {isLoading ? 
            <LoadingScreen/>
        : 
            <Weather weather={weatherCondition} temperature={temperature}/>
        }

    </View>
  )
}

CodePudding user response:

You can use react-native-modal for your loading screen and in animationOut pass this value 'fadeOut'

CodePudding user response:

You can do something like this.

First create a Spinner Component so you can use it wherever you want.

Spinner.js

It take on prop visible to show or hide the ActivityIndicator

import React from "react";
import {
  View,
  StyleSheet,
  ActivityIndicator,
  Modal,
  Dimensions,
} from "react-native";

// dimenstion
const { width, height } = Dimensions.get("window");

const Spinner = ({ visible, ...props }) => {
  if (!visible) return null;
  return (
    <Modal visible={visible} transparent animationType="fade">
      <View style={styles.container}>
        <ActivityIndicator color="white" size={height * 0.07} />
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "rgba(1,0,23,0.65)",
    alignItems: "center",
    justifyContent: "center",
  },
});

export default Spinner;

Now simply use it in your screen

First import it.

import Spinner from '.....';

and Use it like this.

return (
  <View style={styles.container}>
    <Spinner visible={isLoading} />

    <Weather weather={weatherCondition} temperature={temperature} />
  </View>
);
  • Related