Home > database >  Styling Two Elements on Same Line in React Native
Styling Two Elements on Same Line in React Native

Time:11-01

I am trying to style two elements that need to appear on the same line in my react native app. What I have thus far positions them on the same line - using nested <Text> elements - but I'm unclear how to then be able to create some distance between them. For instance, in the example below, I want the icon to be left-aligned, which it is now, but I want the this.props.client.name text to be center-aligned. From my understanding margin is ignored in children elements. How can I accomplish this?

  <View>
    <Text>
      <Feather name="chevron-left" size={24} 
        onPress={() => props.navigation.goBack()} 
     />
     <Text>{this.props.client.name}</Text>
   </Text>
 </ View>

CodePudding user response:

You can try styling them using "flex" css properties.

for example if you have:

<View>
    <Text>
      <Feather name="chevron-left" size={24} 
        onPress={() => props.navigation.goBack()} 
     />
     <Text>{this.props.client.name}</Text>
   </Text>
 </ View>

TRY

<View>
    <Text>
       <View style={{ display: "flex", alignItems: "center", 
         position: "relative", zIndex: 1 }}>
          <Feather name="chevron-left" size={24} 
             onPress={() => props.navigation.goBack()} 
             style={{position: "absolute", zIndex: 2, left: 0 }}
          />
          <Text>{this.props.client.name}</Text>
      </View>
   </Text>
 </ View>

You should now have your Icon on the left and your text centered.

Read more about Flexbox here. reactnative.dev/docs/flexbox

CodePudding user response:

I recommend you remove your Text that wraps your elements.

Then on your View you can change style by setting the flexDirection to row since the default is column in React Native. And the add justifyContent with a value of space-between to position the elements left and right.

Maybe a flex with value 1 is needed not sure.

  • Related