styled-components: gap property not working (React Native)
If I want to set a specific space between items on a flex container, I still need to set individual margin and/or padding to all children instead of simple using the new gap property on the flex container.
Something like this should work (center all MyFlexContainer children and set 10px between each):
import { View } from 'react-native';
import styled from 'styled-components/native';
const MyFlexContainer = styled.View`
flex-direction: column;
justify-content: center;
flex: 1;
gap: 10px;
`
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 30
- Comments: 28 (1 by maintainers)
Make it
Here’s my approach.
Here is what I have been doing to simulate gaps. I basically create a margin on the children and then negate the margin with a negative padding on the parent. The only margin that remains is the one between the children. The reason why I divide the margin and padding by 2 is to stay true to the gap between two children set in the gap constant.
Sadly there is no gap support yet for React Native.
+1 for implementing the gap attribute. Putting styles on each child component is not all that maintainable
Weird comments aside, I can share what I use for this. It has an imperfection though.
This is the API:
It also supports fragments and conditional components:
You can also use a divider component:
Here is the code:
The only downside of this code is that, if the child component returns
null
, it will still add a gap. This is a limitation of React’s top-down approach.yoga pr is completed now
We need this first
https://github.com/facebook/yoga/pull/1116
I confirm gap support is working well with styled-components after upgrading to RN 0.71!
Can confirm that the gap property is working in React Native 0.71 https://reactnative.dev/docs/layout-props#gap
I used the upgrade helper (for my app it was 0.70.6 -> 0.71) here https://react-native-community.github.io/upgrade-helper/?from=0.70.6&to=0.71.0
Update the component from @ozgrozer above a bit. So it is more reusable. Don’t mind the memo if you don’t need it.
I personally use a Gap component
For those stumbling on this thread; I realized
gap
does not work onText
elements for what I was doing. I had to refactor a bit such that I could usegap
onStack
or something else.