react-native:Show spinner at the center of the screen

Viewed 13441

I want to show the spinner at the center of screen.I used alignItems, justifyContent and flex but there is no change in the position then i use margintop for correct positioning.why there is no change on the use of alignItems,justifyContent and flex?

here i m using spinner.

 return (
  <View style={style.spinnerStyle}>
  <Spinner size ="large" />
  </View>
 );
 const style = {
spinnerStyle: {
  flex: 1,
  marginTop:240
}
};

Spinner.js

  import React from 'react';
  import {View,ActivityIndicator} from 'react-native';

  const Spinner = ({size}) => {
  return (
  <View style = {styles.spinnerStyle}>
  <ActivityIndicator size={size || 'large'} />
  </View>
  );
 };

const styles = {
spinnerStyle: {
flex: 1,
justifyContent: 'center',
alignItems:'center'
 }
 };

export { Spinner };
4 Answers
const styles = StyleSheet.create({
    spinnerStyle: { 
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    alignItems: 'center',
    justifyContent: 'center'
 }
});

The correct way to vertically center the ActivityIndicator component is to use 'flex: 1' on the ActivityIndicator component itself, not on its parent component. It does not need a wrapper component and none of the other flex alignment styles are necessary at all.

The improved implementation of the OP's code would be:

import React from 'react';
import {ActivityIndicator} from 'react-native';

const Spinner = ({size}) => {
  return (
    <ActivityIndicator size={size || 'large'} style={{ flex: 1 }}/>
  );
 };

export { Spinner };

Set in spinner parent view:

justifyContent: 'center',
alignItems:'center'

And in spinner set:

alignSelf:'center'   
Related