Reputation: 2162
I want to add same padding/margin to all of my child component(Icon
) just putting style in View
component. How can I achieve?
<View style={{flexDirection: "row",}}>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
</View>
Upvotes: 3
Views: 6556
Reputation: 191
For those trying Marek Lisik's answer, I believe there is a typo in his answer. His code did not work for me until I changed argument to React.Children.map to:
React.Children.map(children, (child) => { /* your code here /* })
Instead of:
React.Children.map((children, child) => {/* this does not work as children is already declared a prop */}
Unfortunately, I cannot comment on his answer since my reputation isn't high enough. Hopefully someone will find my measly answer worthy enough.
Upvotes: 2
Reputation: 2185
It is actually possible for the parent to modify its children. Take a look at the following wrapper component:
const Wrapper = ({ childStyle, children, ...viewProps }) => (
<View {...viewProps}>
{React.Children.map((children, child) =>
React.cloneElement(child, {
style: [child.props.style, childStyle],
}),
)}
</View>
);
// This will add margin to all your stars:
<Wrapper style={{flexDirection: "row",}} childStyle={{margin: 8}}>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
<Icon name={'star'} color={Gold} size={14}/>
</View>
This uses React.Children.map
to iterate over the children the Wrapper
is given, and then React.cloneElement
to transform them and inject the styles we pass from the parent.
Upvotes: 7
Reputation: 2178
Add a style prop to each Icon
<Icon name={'star'} color={Gold} size={14} style={{ margin: 10 }} />
Edit: I don't think you can set a margin from parent component. If you don't want to write the style prop 5 times you can make a custom icon component:
const CustomIcon = ({name, color, size}) => (
<Icon name={name} color={color} size={size} style={{ margin: 10 }} />
)
And then call this component instead of Icon:
<CustomIcon name={'star'} color={Gold} size={14} />
Upvotes: 1