ikenator
ikenator

Reputation: 680

React Native place a text over SVG image

I'm using libraries: "react-native-svg": "12.1.0" & "react-native-svg-transformer": "0.14.3"

import FooIcon from '../assets/images/icons/fooIcon.svg';

<View style={{ flex: 1, paddingTop: 8 }}>
   <FooIcon></FooIcon>
   <View style={{ position: 'absolute', top: 35, bottom: 0, left: 14, right: 0 }} >
      <Text>foo</Text>
   </View>
</View>

How can I have "foo" text centered over the FooIcon. The solution above does not center the text which is important because "foo" text length can change and it has to be in center in every case.

enter image description here

Upvotes: 2

Views: 3146

Answers (2)

redberry
redberry

Reputation: 766

this chunk of code should do the work for you

    <View
    style={{
      justifyContent: 'center',
      alignItems: 'center'
    }}
    >
    <SVG /> //your svg image component goes here
    <Text
      style={{
        position: 'absolute'
      }}
    >
      Test
    </Text>
  </View>

Upvotes: 2

hannojg
hannojg

Reputation: 1117

I would recommend not to use an absolute position if the content size can change dynamically. I would build this with just using flex-box:

...
<View style={styles.itemContainer}>
  <Text>Foo</Text>
  <View style={styles.iconMock} />
</View>
...
const styles = StyleSheet.create({
  itemContainer: {
    alignItems: "center",
    //this has default flex: 0, which means the container will always have the size the children take.
    //we then tell it to centre all the children (items) which gives the needed effect.
  },
  iconMock: {
    backgroundColor: "blue",
    height: 50,
    width: 150,
  }
});

Building it this way the text will always be centred: enter image description here

Upvotes: 0

Related Questions