How to translateX by percentage in React-Native?

Viewed 5844

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.

1 Answers

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.

Related