Eric.M
Eric.M

Reputation: 857

Styling multiple style props with styled-components on React Native

I have been using Styled-components with React web for a while now, but recently I have started working on a React Native app which I decided to use styled-compoents in. It's been great when styling components that have just the style property, such as the default react-native components.

The problem I've been having though is when I need to style a more complex component that has multiple style properties such as containerStyle, inputStyle, and others.

When it's only one style property with a different name I can do the following:

const StyledBadge = styled(({ style, ...rest }) => {
  return <Badge {...rest} containerStyle={style} />;
})`
  position: absolute;
  right: 0;
  top: 0;
`;

This works flawlessly but when the component has multiple styles, I have no idea what to do:

const StyledList = styled(({ style, ...rest }) => {
  return <List {...rest} containerStyle={style} searchInputStyle={?} searchItemStyle={?} />;
})`
`;

With components like Gifted-React-Native-Chat is even worse because it has properties for passing properties as objects to its internal components, such as messageProps, listViewProps, containerProps and all of them have the style property.

Does anyone have any idea how to do that or if it's even possible?

I've been searching and trying to find a solution for this for a few days but I can't.

Thanks!

Upvotes: 3

Views: 1578

Answers (1)

GollyJer
GollyJer

Reputation: 26672

Here's how we ended up doing it.

Styled-components only work with the style prop but many custom components don't expose this prop. Instead they provide a *Style prop that gets passed to child component style props.

As an example, react-native-material-textfield has 5 style props. enter image description here

We use the attrs function to keep the organization of styles in one file with the rest of the styled components.

styled-component attrs example

This doesn't allow you to use traditional css syntax for the pseudo component, but it's the best we could think of to keep all styles organized.

Upvotes: 2

Related Questions