vegemite4me
vegemite4me

Reputation: 6856

React Native: How to stretch TouchableOpacity

I am trying to have two large buttons (TouchableOpacity) be next to each other and take up 50% of the width of the screen.

But they only seem to be as wide as the Text component within them.

enter image description here

How can I make the two TouchableOpacity take up the full width of the screen, with each taking up 50% of the width?

  const styles = StyleSheet.create({
    container: {
      flexDirection: 'row',
      backgroundColor: 'lightblue',
      height: 200,
      justifyContent: 'space-around',
    },
    btn: {
      flex: 1,
      backgroundColor: 'red',
      justifyContent: 'center',
      padding: 20,
      borderWidth: 1,
    },
  });

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.btn}>
        <Text>Left</Text>
      </TouchableOpacity>

      <TouchableOpacity style={styles.btn}>
        <Text>Right</Text>
      </TouchableOpacity>
    </View>
  );

Upvotes: 0

Views: 754

Answers (2)

Matt T
Matt T

Reputation: 138

A possible solution is to use react native's Dimensions

https://reactnative.dev/docs/dimensions

  import { Dimensions } from 'react-native';

  const width = Dimensions.get('window').width;

  const styles = StyleSheet.create({
    container: {
      flexDirection: 'row',
      backgroundColor: 'lightblue',
      height: 200,
      justifyContent: 'space-around',
    },
    btn: {
      width: width*0.5,
      backgroundColor: 'red',
      padding: 20,
      borderWidth: 1,
    },   
  });

Upvotes: 1

Quentin Nippert
Quentin Nippert

Reputation: 107

Try to add a width of 50% to your btn class

  const styles = StyleSheet.create({
    container: {
      flexDirection: 'row',
      backgroundColor: 'lightblue',
      height: 200,
      justifyContent: 'space-around',
    },
    btn: {
      width: '50%',
      backgroundColor: 'red',
      padding: 20,
      borderWidth: 1,
    },
  });

You can also use dimensions from react native and put width: windowWidth/2 on your btn class.

Upvotes: 1

Related Questions