Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my child container taking full width when the parent has a padding on it in my react-native app?

The Problem

I have a simple react native app using styled-components with it.

I have a simple Container that has flex: 1 and a padding: 10px

I also got a child button that has these props: width: 100%; flex-basis: 25%

So my expectation is it should take the full width of it's parent container and then subtracts the 10px on all sides. But it does not. The children takes up the full width of the device as you can see in this screenshot here:

enter image description here

As you can see the orange box is the children but it takes the full width. And I don't get why?

Here is the code snippet (only parts that may cause the problem, SafeAreaView comes from react-navigation and makes sure that the status bar is free):

const Container = styled.SafeAreaView`
  flex: 1;
  background-color: papayawhip;
  align-items: center;
  padding: 10px;
`;

const NewGame = styled.TouchableOpacity`
  background: palevioletred;
  flex-basis: 25%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const Home = () => {
  console.log("hihihoho");
  return (
    <Container>
      <NewGame>
        <NewGameTitle>Neues Spiel</NewGameTitle>
      </NewGame>
      <Title>Up and running!</Title>
    </Container>
  );
};

So at this point I debugged the app and toggled the inspector and can clearly see the padding but the child still takes up the whole width.

Do you guys know why?

Edit: I added in another Container with a styled.View and set yet another flex: 1 and padding: 10px. Now this workaround seems to work. I think it has something to do with react-navigation's SafeAreaView

like image 768
GeraltDieSocke Avatar asked Dec 04 '25 08:12

GeraltDieSocke


1 Answers

Try giving padding to the child component. Also you can try giving dynamic width to the button like Dimension.get(window).width - 20 and style as alignSelf:'center'.

This might work

like image 105
Rishav Kumar Avatar answered Dec 07 '25 04:12

Rishav Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!