Giter Site home page Giter Site logo

react-native-user-avatar's Introduction

React Native User Avatar

npm version npm downloads Build Status

Coverage lines Coverage functions Coverage branches Coverage statements

A bare-bones user avatar display with support for falling back to using the user's initials on a colored background as the avatar. Based on the great library for React: https://github.com/wbinnssmith/react-user-avatar, and ported to React Native.

iOS Screenshot Android Screenshot

Installation

npm install --save react-native-user-avatar or yarn add react-native-user-avatar

Usage

The fallback avatar's color may be set by passing in the bgColor prop, or you can customize the range of colors used by passing in an array of bgColors. The component uses a simple calculation to consistently use the same color for the same user's name every time.

UserAvatar Component

import UserAvatar from 'react-native-user-avatar';

const App: () => React$Node = () => {
  return (
    <>
    ...
    <View>
      <UserAvatar size={100} name="Avishay Bar" />
      <UserAvatar size={100} name="Avishay Bar" src="https://dummyimage.com/100x100/000/fff" />
      <UserAvatar size={50} name="John Doe" bgColors={['#ccc', '#fafafa', '#ccaabb']}/>
      <UserAvatar size={50} name="John Doe" />
      <UserAvatar size={50} name="Jane Doe" bgColor="#000" />
    </View>
    ...

UserAvatar Props

Attribute Type Default Value Description
name string 'John Doe' name used for generating initials
src string undefined source image on the internet to display
bgColor string undefined custom background color for the initials
bgColors array see index.js custom array of background colors to choose from
textColor string '#fff' custom text color for the initials font
size number 32 custom size that defines both the avatar and the initials font size
imageStyle object undefined custom image styling to append to the Image component displays the source image
textStyle object undefined custom text styling to append to the Text component that displays initials
style object undefined custom style to append to the UserAvatar component container
borderRadius number size * 0.5 custom border radius for the component
component React.Component undefined custom component to display instead of initials or source image

Contributing

Contributions are welcome. Please see CONTRIBUTING.md if you like to contribute to this library.

Credits

@wbinnssmith for creating https://github.com/wbinnssmith/react-user-avatar

License

MIT

react-native-user-avatar's People

Contributors

alvinmatias69 avatar arelstone avatar avishayil avatar dependabot[bot] avatar harveyappleton avatar heshanlk avatar itinance avatar jerome91410 avatar jlpujante avatar luizeduard0 avatar macavity23 avatar martin25699 avatar walidvb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-native-user-avatar's Issues

Why does it require me to install a lot of extra packages

when I installed the package on my expo application, once imported the application broke coz I need to install url package
then broke again coz I need to install http package any my guess this won't be the end of it

this is the error I keep getting

http could not be found within the project or in these directories:
  node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
   8 | var parse_url = require('url').parse;
   9 | var resolve_url = require('url').resolve;
> 10 | var http = require('http');
     |                     ^
  11 | var https = require('https');
  12 | var zlib = require('zlib');
  13 | var stream = require('stream');

component property is not working properly

import { CachedImage } from 'react-native-cached-image';

const avatarImage = (
        <CachedImage
                source={{
                        uri: this.props.userAvatar
                                ? `${avatarUrl}/${this.props.userAvatar}/downloadMedia`
                                : null
                }}
        />
);

<UserAvatar
        size="50"
        name={this.props.fullname}
        color={'#9B9B9B'}
        style={[styles.avatar, { padding: 2 }]}
        component={avatarImage}
/>

The component property is not working. not showing anything. I also tried with built-in <Image />, still no luck.

Typescript support

When i install the library in a Typescript project, I get the following error

Could not find a declaration file for module 'react-native-user-avatar'. '/Users/lyqht/project/node_modules/react-native-user-avatar/lib/module/index.js' implicitly has an 'any' type.

Could not get abbr from name

Looks like another user was having the same issue, but they closed the ticket—#56

Initials are rendering just fine, but this warning gets spammed intermittently.

if (!abbr) {
console.warn('Could not get abbr from name');
abbr = name;
}

Since default props are set, you could always fallback to 'JD'—it looks like the root issue is somewhere in the initials package.

Can I pass headers with authorization token to the src?

Can I pass headers with authorization token to the src?

My images are in an URL protected accessed only via token, how can I do it?

Ex:

{"headers": 
  {"Authorization": "Bearer Mjc1MD
U2LCJuYmYiOjE2MTIyNjQyNTYsImp0aSI6IkVOb3JqZUpmbzduakFkNTEifQ.JD_nWRY1HK0K7Hve26iSqbI7cvZtKkUKLjKBOU4P1uE", "X-Gateway-Server": "some server"
}, "method": "GET",
"uri": "http://some_url/image.jpg"}

Online fetched source is not a supported image

{
    "react-native": "^0.62.2",
    "react-native-user-avatar": "^1.0.7"
}
const src = "https://dffqb1y6phusm.cloudfront.net//eyJidWNrZXQiOiJzY2hkbHJhc3NldHMtcHJvZCIsImtleSI6InB1YmxpYy9iYW5uZXIvSU1HLTIwMjAwNDMwLTMyVjVjckNiRiIsImVkaXRzIjp7InJlc2l6ZSI6eyJ3aWR0aCI6MTAwLCJoZWlnaHQiOjEwMCwiZml0IjoiY292ZXIifX19";
<UserAvatar
  name={name}
  size={size}
  src={src}
/>

I get the warning below in console
Online fetched source is not a supported image;

Note: It loads google account avatars normally. Maybe a problem with RN, I'm not sure.

Extra

I noticed this component is not as circular as I percieved it in earlier version. I can see a little bit of the background color along the border.

My current solution

<UserAvatar
  name={name}
  // dont add 'src' prop to prevent borderWidth of 1
  style={{ // Add this to give a more circular shape
     width: size,
     height: size,
  }}
  size={size} // You still need this to keep the container circular
  component={
     src ? (
     <Image source={{uri: src}} style={{
         width: size + 1, // Adding 1 to prevent background border from leaking
         height: size + 1,
         borderRadius: size / 2
     }}/> ) : undefined
  }
/>

Not Dynamic

if i do something like this
<UserAvatar name="John Doe" size={100} color="#6c5ce7" /> it works fine.

But if i do something like
<UserAvatar name={this.state.provider_name} size={100} color="#6c5ce7" /> it says the Avatart requires a name.

Please what do i need to do?
Thanks

Contributing Guidelines?

Hi I'm interested in helping this project. Do you have any contributing guidelines for me to follow? What kind of help do you expect? Thanks

Add support for web

Currently, the avatar fails to render on web.

From my debugging, it comes from the fetch API being called in a way that is not supported by browser.
Specifically, in helper.js:

fetchCall.headers.map does not exist.
To be honest, I can't find any reference to this API nor in mdn headers, nor in nodejs fetch implementation, so i really don't know where this .map comes from (also, the other Headers API are missing. really baffled by this).

I'll submit a PR to add web support

Online fetched source is not a supported image

I am getting an warning when using Amazon S3 public urls as the source for an avatar. I can handle the warning, but the image won't load, even though the link is to a valid image that will load in a standard react-native tag. It might be because my S3 links do not have a file extension, and so Amazon is not returning a content type header.

In helpers.js, on line 41, there is a conditional statement that returns false if contentTypeHeader does not start with image/. Can that check be removed, or can you add a property to ignore that check , like ignoreContentTypeCheck: true or something like that?

I cloned this repo and removed the check the myself for contentType on line 41 in helpers.js and it works great.

textStyle prop is not showing any effect

Blow is my my code for avatar

   <UserAvatar style={avatarStyle} name={displayname} textStyle={avatarTextStyle} textColor={'black'} />

And textStyle is as shown below

  avatarTextStyle: {
      fontFamily: 'OpenSans-Bold',
      fontSize: 24,
      lineHeight: 33,
      color: '#1A7AF3',
  }

But this style is not showing any effect at all. no change in fontSize, font color.

Version: "react-native-user-avatar": "^1.0.7",

Fallback not working

When I render proper image:

<UserAvatar size="100" name="Avishay Bar" src={"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03ds.jpg"}/>

... it is working fine.
But if I make an error in URL which results in 404 then avatar is blank (no letters)

<UserAvatar size="100" name="Avishay Bar" src={"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat0"}/>

Extend useEffect to render the image in case it changes

Hi,

Great improvements on the package, thanks for taking the time to share it with us.

I have a suggestion though in src/index.js line 50 to extend the useEffect for changes to src prop. E.g useEffect(() => // magic here),[src]);;

I'm not quite sure if my assumption is right but I have a case of an image upload that fails to re-render because this effect works only when component is mounted.

Should you have further questions, please let me know.

Ciprian

Border-Radius is wrong on iOS

As shown in the screenshot, on iOS the border-radius is calculated wrong. It needs to be calculated depending on the radius of the avatar: size * 0.5

screen shot 2017-01-19 at 17 25 36

Typescript declarations

Hey,

sorry for not preparing a PR (as I am not sure about the proper way to include typings into a module), but here are my TS module declarations for this package:

declare module 'react-native-user-avatar' {
  import { StyleProp, ImageStyle, ViewStyle } from 'react-native'

  const component:React.ComponentType<{
    name: string;
    src?: string;
    bgColor?: string;
    bgColors?: string[];
    textColor?: string;
    size?: number;
    imageStyle?: StyleProp<ImageStyle>;
    style?: StyleProp<ViewStyle>;
    borderRadius?: number;
    component?: React.ComponentType;
  }>;

  export default component;
}

Avatar Initials gets a misplaced UI

Issue:

Avatar Initials UI gets misplaced when the "name" property is provided with a string which a has multiple capital alphabets.

Step to Reproduce :

<UserAvatar size="100" name="AVISHAY" src="" />

or,

<UserAvatar size="100" name="AVISHAY BAR" src="" />

Animation

How can we dynamically resize the User avatar component with animation?

Warning: Failed prop type: Invalid prop `style` of type `number` supplied to `UserAvatar`, expected `object`

I encountered this while trying to pass style object created by StyleSheet.create() to UserAvatar. It show this warning because of optimisation that StyleSheet.create does, where it returns number instead of object

index.js:1 Warning: Failed prop type: Invalid prop `style` of type `number` supplied to `UserAvatar`, expected `object`.
    in UserAvatar (at User.js:13)
    in Avatar (at User.js:34)

Should be fixed by using ViewPropTypes from react-native or some module like react-style-proptype

textStyle prop not working. Also cannot find type declarations

Using version v1.0.8.

<UserAvatar
      size={90}
      name={`${card.firstName} ${card.lastName}`}
      src={card.profilePicUrl}
      borderRadius={90 / 2}
      style={{
          borderColor: "#00A5B9",
          borderWidth: 3,
      }}
      textStyle={{
          fontFamily: 'OpenSans-Bold',
          fontSize: 20,
      }}
/>

Referred to these two issues first (#62 and #60 ) where it was mentioned it was resolved in v1.0.8 but I am still getting the issue.

Here's how the types are referenced in package.json for react-native-user-avatar in v1.0.8

"react-native": "src/index.js",
  "types": "lib/typescript/src/index.d.ts",
  "files": [
    "lib/",
    "src/"
  ],

Setting image caused warning about an unmounted component during an async callback

I ran into this with another component that I built called NetworkImage. Basically the async call to set the image comes back after the component is unmounted, causing a yellowbox warning. My solution was to add useRef, and just pass a boolean in as an initial value. Forked this repo and can verify that this works.

// add reference to DOM like object
  const isMounted = useRef(true);

  useEffect(() => {
    if (component) setInner(<CustomAvatar size={size} component={component} />);
    if (src) {
      const controller = new (AbortController || window.AbortController)();
      fetchImage(src, {signal: controller.signal}).then((isImage) => {
      // make sure it's still there
        if (isImage && isMounted.current) {
          setInner(
              <ImageAvatar src={src} size={size} imageStyle={imageStyle} />,
          );
        }
      });
      return () => {
        controller.abort();
        // cleanup code, prevents changing the state on an unmounted component
        isMounted.current = false;
      }
    }
  }, []);

Text styling doesn't work

The textStyle prop doesn't seem to work.

Maybe the TextAvatar is missing this prop l.63 in index.js.
The prop is in the initial state but the useEffect seems to erase it

Allow providing custom styles

Something like:
<UserAvatar size="70" style={{marginRight:15}} name={item.name} src={item.photo} />
Should be achievable allowing passing style?:StyleProp to your component. Thank you.

On Error

how to solve if the invalid image url will be transferred directly to the text ?

[web] Images with specific CORS headers give false negative

I'm loading images from gravatar, and it seems that using the fetch API returns an error, even though the image would be correctly loaded by the browser.

I'll try and make a PR to address this, by changing the behaviour on web, along the lines of:

 const image = document.createElement('img');

  image.onload = setImageWorked;
  image.onerror = doUseFallback;
  image.referrerPolicy = 'no-referrer';
  image.src = src;

Could not get abbr from name

I have that error when i use something like this:
<UserAvatar name={displayName} style={[styles.authorPhoto, { ...props.style }]} />

It's an infinite cycle.

Error fetching source

The purpose of this fix is to remove an unnecessary warning displayed in the following screenshot.

Screen Shot 2022-07-19 at 10 10 59 PM

This warning simply states that the avatar can not find a source url for a profile image and will fall back to the user's initials. This is the desired behavior of the component and therefore, a warning is not needed.

Abort downloading when unmount is triggered

When you have bad network and/or the image to display is too hughe, it could be nice to abort fetch downloading when you unmount the component.

It will fix an error found on my project:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Capture d’écran 2020-05-18 à 15 30 28

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.