I’m new to React, and am trying to center an <Image />
component within a larger <View />
, per below:
import { Image, View } from 'react-native';
<View
style={{
width: 48,
height: 48,
alignSelf: "center",
justifyContent: "center",
alignItems: "center",
position: "relative",
}}
>
<Image
style={{
width: 32,
height: 32,
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
margin: "auto",
}}
source={spinner}
/>
</View>;
But instead of being centered, it is positioned on top left within <View />
.
The above css would have worked in HTML, but what am I missing for React Native? Btw I have to use absolute position for the Image to overlay on other components inside <View />
.
Thank you,
3
Answers
Adding this on your child element along with absolute will solve the issue.
top: ‘50%’,
left: ‘50%’,
transform: "translate(-50%, -50%)"
You’ve assigned
top
andleft
values to0
which positions it to top-left.This should work:
I think the easiest would be to think of a new
View
as your overlay instead of theImage
itself.If the
alignSelf
,justifyContent
, andalignItems
on the parentView
were added for theImage
, they can be removed.