Soccerball123
Soccerball123

Reputation: 869

Unsure why button is not in the center in react native

I recently started programming in react native and I'm trying to implement a button located in the bottom center of the screen that will capture an image once it is pressed. Right now when I run the app on my phone, the red button I created is appearing on the left bottom side even though I centered it using alignItems: 'center' in the stylesheet. I tried using right: '50%' in the stylesheet to see if it would appear in the middle of the screen but it didn't. I'm not sure what to do now, here is my code:

import { Camera } from 'expo-camera';
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Button, Alert, TouchableNativeFeedback, Image, SafeAreaView } from 'react-native';




export default function App() {
  const buttonClickedHandler = () => {
    console.log('Picture Taken');
  };


  // Camera Permissions
  const [hasPermission, setHasPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View style={styles.container}>
      <Camera style={styles.camera} type={type} />
      
      //BUTTON
      <TouchableOpacity
          onPress={buttonClickedHandler}
          style={styles.pictureButton}>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  pictureButton: {
    width: 90,
    height: 90,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
    borderRadius: 100,
    backgroundColor: 'red',
    position: 'absolute',
    bottom: 20,
  },
  container: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  text: {
    fontSize: 18,
    color: 'white',
  },
});

Upvotes: 0

Views: 357

Answers (1)

Emi C
Emi C

Reputation: 26

Absolute positioned elements are removed from the document flow, so properties like alignItems: 'center' are ignored.

Try using something like this:

 pictureButton: {
    width: 90,
    height: 90,
    padding: 10,
    borderRadius: 100,
    backgroundColor: 'red',
    position: 'absolute',
    bottom: 20,
    left: 50%,
    transform: translateX(-50%),
  }

Here is an in depth explanation on how absolute positioning works

Upvotes: 1

Related Questions