Search code examples
javascriptcssreact-nativereact-native-stylesheet

Displaying line bellow TouchableOpacity options wrapped in a View at the border of parent


I have a menu like component in React Native, which is wrapped in a View. This View has 3 options. I would like each option to have a line below it almost touching border of the view.

In order to achieve this I have three TouchableOpacities with Text and a View, all wrap under the same parent. This is what my code looks like:

export function Menu () {
  return (
    <View style={{
      flex: 1,
      flexDirection: 'row',
      backgroundColor: 'grey',
      height: 50,
      justifyContent: 'space-around',
      alignContent: 'center',
      alignItems: 'center'
    }}>
      <TouchableOpacity>
        <Text>Option 1</Text>
        <View
          style={{
            width: 50,
            height: 4,
            backgroundColor: 'red',
            paddingTop: 0,
            marginTop: 25,
            marginBottom: 0
          }}
        />
      </TouchableOpacity>
      <TouchableOpacity> <Text>Option 2</Text> </TouchableOpacity>
      <TouchableOpacity> <Text>Option 3</Text> </TouchableOpacity>
    </View>
  )
}

The issue here is that by placing the inner View at the bottom through marginTop: 25, I push my text to the top of their parent, which I do not want. Here is the result of this code:

enter image description here

See how Option 2 and Option 3 are centered within their parent? That is exactly how I want Option 1 to be, but with the red line right on the edge of the grey box wrapping all three options.

How can this be achieved?


Solution

  • wrap the <Text> inside a a <View>. Its been quite some time since I last worked on RN but I think this code should give you the desired result.

    <TouchableOpacity>
      <View style={{flex: 1, alignItems: 'center', height: 46}}><Text>Option 1</Text></View>
      <View
          style={{
            width: 50,
            height: 4,
            backgroundColor: 'red',
            paddingTop: 0,
            marginTop: 25,
            marginBottom: 0
          }}
        />
    </TouchableOpacity>
    

    PS: I think it should work even without the height: 46 for the <View> but I can't test it at the moment so can't assure.