1
votes

I am learning React Native and styled components. I am working on a simple iOS app and facing some problems with styled-components.

What I'm trying to do

I am trying to show modal on click which looks like this

<Modal visible={this.state.isModalVisible} animationType={'fade'}>
    <StyledView flex={1} padding={10} backgroundColor={'orange'}>
        <View>
            ...more Views and Texts
        </View>
    </StyledView>
</Modal>

StyledView is a custom view that I have created using styled-components which looks like this

const ViewWrapper = styled.View`
  flex: ${props => props.flex};
  padding: ${props => props.padding};
  backgroundColor: ${props => props.backgroundColor};
`;

const StyledView = ({ flex, padding, backgroundColor }) => (
  <ViewWrapper
    flex={flex}
    padding={padding}
    backgroundColor={backgroundColor}
  />
);

export default StyledView;

Problems I'm having

1) When I set padding={10}, I get an error Failed to parse declaration "padding: 10".

2) After Googling a bit, I found that I should be using padding={'10px'} which throws this error, 10px is of type NSString cannot be converted to YGValue. Did you forget the % or pt suffix?.

(padding={'10%'} works fine)

Then I simply tried setting flex and padding values in ViewWrapper and send only background color as prop.

3) But for some reason, Views and Texts nested within StyledView does not show up.

Please tell me why it's not working and help me understand what I'm missing here. Thanks.

1

1 Answers

0
votes

You have a couple of issues.

  1. Styled Components do not accept strings in them, so you cannot sent the '10px' from the prop.
  2. You are correct that padding needs a px at the end. Something padding alone does not work, but you can workaround it by adding paddingVertical and paddingHorizontal with the same value which is the same as padding.
  3. You are overcomplicating the implementation as you dont need to pass the style props and you can define them all within your styled component. Like this:

import styled from "styled-components/native"

const StyledView = styled.View`
   flex: 1;
   padding: 10px;
   backgroundColor: orange
`;

And then you just use it like this:

<Modal visible={this.state.isModalVisible} animationType={'fade'}>
    <StyledView>
        <View>
            ...more Views and Texts
        </View>
    </StyledView>
</Modal>

No need for the ViewWrapper or more props. Also, and this is just personal. I only use StyledComponents for the ones that could change at run time or depend on a theme, like exts for fontFamily or fontSize. For the rest that have constant styles that never change, I just use normal styles objects since it is less verbose.

If this is a simplified version and you absolutely need the props you con move them all into one single theme object and pass it with a ThemeProvider and then just read it as ${props.theme.backgroundColor} or something.

Cheers