Wasteland
Wasteland

Reputation: 5399

React-native: position elements in the center and flex-end

Is it possible to have the following layout (without resorting to absolute positioning)?

|...........centreElement.......RightElement|

So as if the justifyContent was 'space-between' but without the first element. I also thought to 'justifyContent: 'centre'' and then try 'justifySelf: 'flex-end' on the RightElement but this property does not exist.

<View styles={styles.container}>
  <Text>centreElement</Text>
  <Text>RightElement</Text>
</View>

container: {
    flexDirection: 'row',
    justifyContent: 'center'
}

Upvotes: 0

Views: 1296

Answers (2)

Alok
Alok

Reputation: 9018

An ideal solution without using absolute. The CentreElement text might not comes at the center, but without absolute, you cannot align it either, since you are not giving the content to take up the 100% width which is needed to rightly align the content to center. Following steps can give you the satisfying results:

  • Just give out flexDirection: 'row' to the container
  • Give both the text CentreElement and RightElement 50% width
  • Align both of them to right, and done!!

Code:

export default function App() {
  return (
    <View style={styles.container}>
      {/* Txt container*/}
      <View style={styles.textContainer}>
        <Text style={styles.text}>
          CentreElement
        </Text>
        <Text style={styles.text}>
          RightElement
        </Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  textContainer: {
    width: '100%',
    flexDirection: 'row'
  },
  text: {
    textAlign: 'right', 
    width: '50%', 
    fontSize: 16, 
    fontWeight: 'bold'
  }
});

Result:

Resultant Screenshot

Upvotes: 1

Dipan Sharma
Dipan Sharma

Reputation: 1133

There is mistake in your code please update code from <View styles={styles.container}> to <View style={styles.container}>

Please try the following code:

<View style={styles.container}>
     <View style={{ flex: 1 }} />
     <View style={{ flex: 1 }}>
        <Text>centreElement</Text>
     </View>
     <View style={{ flex: 1 }}>
        <Text>RightElement</Text>
     </View>
</View>

Upvotes: 2

Related Questions