Home > Software engineering >  How to change the image size in a reusable component?
How to change the image size in a reusable component?

Time:01-14

In my React Native application, I have a 48 x 48 profile picture component that is in the header on all of the screens.

ProfilePicture.jsx

const ProfilePicture = () => {
  return (
    <>
      <Image style={styles.profPic} source={{ uri: userObj?.avatar }} />
    </>
  );
};

const styles = StyleSheet.create({
  profPic: {
    minHeight: 48,
    minWidth: 48,
    borderRadius: 100,
    shadowColor: "#000",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1.0,
    shadowRadius: 3.84,

    elevation: 5,
  },
});

export default ProfilePicture;

Now, I want to use a larger version in my user settings screen where the user can change their profile image.

My thought was that by setting the style in the imported component, it would show a larger version of the image:

<ProfilePicture style={{ width: 100, height: 100 }} />

However, the image remains the same size. I know I could just create another component with the required size for this page, but since the image comes from a remote server, I don't want to call the URL multiple times.

How can I do this just using my current component?

CodePudding user response:

A good way to handle this would be to pass in a style prop to your ProfilePicture component. That way any component using the ProfilePicture component would be able to overrule the default styling. Combine this with the fact that the style prop of react-native components can take in arrays as value, and the code is pretty clean

const ProfilePicture = ({ style }) => {
  return (
    <Image style={[styles.profPic, style]} source={{ uri: userObj?.avatar }} />
  );
};

const styles = StyleSheet.create({
  profPic: {
    minHeight: 48,
    minWidth: 48,
    borderRadius: 100,
    shadowColor: "#000",
    shadowOffset: {
      width: 2,
      height: 2,
    },
    shadowOpacity: 1.0,
    shadowRadius: 3.84,

    elevation: 5,
  },
});

export default ProfilePicture;

Your example code will then work as intended

<ProfilePicture style={{ width: 100, height: 100 }} />
  •  Tags:  
  • Related