Home > Software design >  Passing image URL to functional component in React native
Passing image URL to functional component in React native

Time:02-03

I want my avatar component to show the avatar with the URL passed to the component. So if I pass avatar1 it shows avatar1. I have tried several methods, but nothing seems to work.

My avatar component looks like this currently. I want to get rid of the static URL

export default function Avatar() {

  return (
    <Image source={require("../assets/avatar.png")} style={styles.avatarStyle} />
  );
}
const styles = StyleSheet.create({
  avatarStyle: {
    resizeMode: 'contain',
    height: "60%",
    alignSelf: "flex-start",
    position: "absolute",
    bottom: 0
  }
});

CodePudding user response:

Probably you trying to pass this avatar1 via props so you need to use the props, passing it to the function

export default function Avatar({avatarUri}) {
    
      return (
        <Image source={{uri: avatarUri}} style={styles.avatarStyle} />
      );
    }
    const styles = StyleSheet.create({
      avatarStyle: {
        resizeMode: 'contain',
        height: "60%",
        alignSelf: "flex-start",
        position: "absolute",
        bottom: 0
      }
    });

https://reactnative.dev/docs/props

CodePudding user response:

Make sure the next things:

  • Image path check correct path
  • You should add the width style param to the image, it is required to render.
  • resizeMode it's a prop of Image, not a style param

Fixed style:

const styles = StyleSheet.create({
  avatarStyle: {
    height: "60%",
    width: 150, // FOR EXAMPLE
    alignSelf: "flex-start",
    position: "absolute",
    bottom: 0
  }
});

The complete code:

export default function Avatar() {

  return (
    <Image source={require("../assets/avatar.png")} style={styles.avatarStyle} resizeMode='contain'/>
  );
}
const styles = StyleSheet.create({
  avatarStyle: {
    height: "60%",
    width: 150, // FOR EXAMPLE
    alignSelf: "flex-start",
    position: "absolute",
    bottom: 0
  }
});
  •  Tags:  
  • Related