8

I am trying to horizontally centre an absolutely positioned component in React-Native which I do not know the width of.

In css I can do this with:

position: absolute;
left: 50%,
transform: translateX(-50%);

But when I do the equivalent in React-Native it only transforms left by 50 instead of 50%. Also because I'm trying to centre the navigation bar in Tab.Navigator I don't think I can wrap it in a parent component:

<Tab.Navigator
  barStyle={{
    position: "absolute",
    width: "95%",
    left: "50%",
    transform: [{ translateX: "-200" }],
    bottom: 5,
    overflow: "hidden",
    borderRadius: "50%",
  }}
>

EDIT The component I am trying to centre is the <Tab.Navigator> navigation bar.

Kirill Novikov
  • 2,576
  • 4
  • 20
  • 33
Ken
  • 1,155
  • 2
  • 19
  • 36
  • 1
    position: "absolute", width: "100%", textAlign: "center", or use alignItems: "center" – Daphaz Apr 28 '21 at 01:06
  • Thanks but I don't want to set the width to 100% – Ken Apr 28 '21 at 01:08
  • oh maybe use the marginHorizontal : "auto", but i don't see your component it is in a view ? the ideal would be to post some of your component – Daphaz Apr 28 '21 at 01:12
  • Unfortunately marginHorizontal didn't work, I added an edit ^ the component I am trying to centre is the navigation tab, it is not in any other view but I want to set the width to 95% and centre horizontally – Ken Apr 28 '21 at 01:19
  • 1
    mmm look [Here](https://stackoverflow.com/questions/37317568/react-native-absolute-positioning-horizontal-centre) – Daphaz Apr 28 '21 at 01:23
  • Unfortunately since I'm working with Tab.Navigator I don't think I can wrap it in another tag... (I tried it but the whole page just went blank) – Ken Apr 28 '21 at 01:34
  • @Ken i've tested with no problem, by default react navigation will center the tab bar label horizontally. Could you create a snack with your code? – Quang Thái Apr 28 '21 at 03:54
  • https://snack.expo.io/R4IBoau6d let me know if this works, it's my first time making a snack – Ken Apr 28 '21 at 04:17

1 Answers1

2

Since you know that the Tab.Navigator is going to have a width of 90%, you could set the left value to be 5% to center it in the screen without having to use translate.

<NavigationContainer>
  <Tab.Navigator
    initialRouteName="Home"
    activeColor={'purple'}
    inactiveColor={'gray'}
    barStyle={{
      left: '5%', // <- this will center the navbar
      position: 'absolute',
      width: '90%',
      bottom: 20,
      overflow: 'hidden',
      borderRadius: '20%',
      backgroundColor: 'white',
    }}>
    <Tab.Screen name="Home" component={HomeScreen} />
    <Tab.Screen name="Camera" component={CameraScreen} />
    <Tab.Screen name="Profile" component={ProfileScreen} />
  </Tab.Navigator>
</NavigationContainer>

If you need better control, you will have to measure the device width, item width and adjust the left value to make sure it's centered.

nipuna-g
  • 6,252
  • 3
  • 31
  • 48