skip to Main Content

I want to align items center of page. I use justifyContent on all css styles but it doesn’t work. I want to align them dynamically. I don’t want to use marginTop:xxx. I want to align all items when i add a new category or new categories to application. I want to align them with alignItems, justifyContent etc.


const CategoriesScreen = () => {
  const [categories, setCategories] = useState<ICategories>()
  const navigation:any = useNavigation();
  const [select, setSelected] = React.useState<boolean>(true);

  useEffect(() =>{
  fetchCategories();

  },[])

  const fetchCategories = async () =>{
    try {
      setCategories((prevState) => ({
        ...prevState,
        pending:false,
        errorMsg:""
      }));
      const categories = await fetch('https://fakestoreapi.com/products/categories');
      const categoriesJson = await categories.json();

      setCategories((prevState) =>({
        ...prevState,
        categories : categoriesJson,
        pending:false,
        errorMsg:""
   
      }));


    } catch (err) {
      console.log("Error :", err)
    }
  }

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

      <FlatList
        data={categories?.categories}
        renderItem={({item}) => 
        <Pressable 
        onPress={() => alert("deneme")}
        style={({ pressed }) => [
          { backgroundColor: pressed ? 'red' : 'transparent' },
          styles.categoriesStyle
          
      ]} 
          >
          <Text >{item}</Text>
        </Pressable>}
        keyExtractor={(item, index) => index.toString()} 
        />
  
    </View>
  )
}

export default CategoriesScreen;

const styles = StyleSheet.create({
  container: {
    flex:1,
    backgroundColor:"white",
    alignItems:"center",
    justifyContent:"center"
  },

  categoriesStyle:{
    flex:1,
    backgroundColor:"lightgray",
    margin:"5%",
    textAlign:"center",
    borderRadius:20,
    width: 300,
    padding:"10%",
    justifyContent:"center",
    alignItems:"center"
  }
}) 

I tried justifyContent and alignItems but they didn’t work.

2

Answers


  1. I am not familiar with React Native so I can be very wrong but just in case — have you set up display: flex elsewhere?

    Login or Signup to reply.
  2. You’ve to added a contentContainerStyle prop of the FlatList component. This style ensures that the content of the FlatList is centered both horizontally and vertically within its container.
    Like this:-

    const CategoriesScreen = () => {
      const [categories, setCategories] = useState<ICategories>();
      const navigation: any = useNavigation();
      const [select, setSelected] = React.useState<boolean>(true);
    
      useEffect(() => {
        fetchCategories();
      }, []);
    
      const fetchCategories = async () => {
        try {
          setCategories((prevState) => ({
            ...prevState,
            pending: false,
            errorMsg: "",
          }));
          const categories = await fetch(
            'https://fakestoreapi.com/products/categories'
          );
          const categoriesJson = await categories.json();
    
          setCategories((prevState) => ({
            ...prevState,
            categories: categoriesJson,
            pending: false,
            errorMsg: "",
          }));
        } catch (err) {
          console.log("Error :", err);
        }
      };
    
      return (
        <View style={styles.container}>
          <FlatList
            data={categories?.categories}
            renderItem={({ item }) => (
              <Pressable
                onPress={() => alert("deneme")}
                style={({ pressed }) => [
                  { backgroundColor: pressed ? "red" : "transparent" },
                  styles.categoriesStyle,
                ]}
              >
                <Text>{item}</Text>
              </Pressable>
            )}
            keyExtractor={(item, index) => index.toString()}
            contentContainerStyle={styles.listContent}
          />
        </View>
      );
    };
    
    export default CategoriesScreen;
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: "white",
        alignItems: "center",
        justifyContent: "center",
      },
    
      listContent: {
        flexGrow: 1,
        justifyContent: "center",
        alignItems: "center",
      },
    
      categoriesStyle: {
        backgroundColor: "lightgray",
        margin: "5%",
        textAlign: "center",
        borderRadius: 20,
        width: 300,
        padding: "10%",
        justifyContent: "center",
        alignItems: "center",
      },
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search