skip to Main Content

I would like to give a default value to my component Avatar from React Native Elements because I have not prepared all the icons files required. However, when I use the OR logic, it fails to work. What is the proper way to do that?

          {sites.map((key) => {
            return (
              <Avatar
                size={32}
                containerStyle={{ margin: 0, padding: "0.1em" }}
                rounded
                source={
                  require("../../assets/" + utils.getPathName(key.properties.nameEN, "icon.png")) ||
                  require("../../assets/default/icon.png")
                }
                onPress={() => {
                  displayModal(key);
                }}
              />
            );
          })}

2

Answers


  1. This is what I would do:

    var IMG;
    try {
        IMG = require("../../assets/" + utils.getPathName(key.properties.nameEN, "icon.png"));
    } catch (e) {
        IMG = require("../../assets/default/icon.png");
    }
    
    {
      sites.map((key) => {
        return ( 
        <Avatar 
        // other props...
          source = {IMG}
        />);
      })
    }
    Login or Signup to reply.
  2. If your icons will change through time, you’ll have to use state.

    Also, you may want to use Image instead of Avatar to better handle onError events.

    const icon = require("../../assets/" + utils.getPathName(key.properties.nameEN, "icon.png");
    const temp_icon = require("../../assets/default/icon.png");
    
    const MyAvatar = ({ source, size }) => {
      const [avatarSource, setAvatarSource] = useState(source || temp_icon);
    
      const handleImageError = () => {
        setAvatarSource(temp_icon);
      };
    
      return (
        <Avatar
          size={32}
          containerStyle={{ margin: 0, padding: "0.1em" }}
          rounded
          renderAvatar={() => (
            <Image
                source={avatarSource}
                onError={handleImageError}
            />
          )}
        />
      );
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search