Search code examples
reactjstypescriptformikchakra-ui

Chakra Ui Avatar Background Color Not Showing Up


I am creating a project management application that allows users to create profiles and optionally add profile pictures to their profile. I'm using Chakra Ui as my component library. In many parts of the application, a user is represented by a Chakra Ui avatar that is supposed to display a users profile picture if there is one, and if not, display their initials with a random background color. The issue I'm having is that sometimes if a user does not have a profile picture, then the avatar displays their initials but there is no background color (it's just white). I can manually add a background color which works, but this means that every avatar without a profile picture has the exact same background color. I want the random color feature of the Chakra avatar to work as intended.

I created a UserDropdown component that displays users with their name and avatar. This component is used in Formik forms where the initial value is a user, but you can select different users that are on the project. This component is primarily where I am experiencing this issue.

import { Avatar, Button, Flex, FormControl, Menu, MenuButton, MenuItem, MenuList, Text } from "@chakra-ui/react";
import { ProjectParticipant } from "../../../models/ProjectParticipant";
import { useField, useFormikContext } from "formik";
import { useEffect } from "react";

interface Props {
    name: string
    options: ProjectParticipant[]
    allowNull?: boolean
    submitOnSelect?: boolean
}

export default function UserDropdown({ name, options, allowNull, submitOnSelect }: Props) {
    const [field, meta] = useField(name);
    const { setFieldValue, submitForm } = useFormikContext();

    const filteredOptions = options.filter(option => option.userId !== field.value?.userId);

    const handleSelectionChange = (option: ProjectParticipant | null) => {
        setFieldValue(name, option);
        if (submitOnSelect) {
            submitForm();
        }
    }

    useEffect(() => {
        console.log('field value:', field.value);
    }, [field.value]);

    return (
        <FormControl width="fit-content" isInvalid={meta.error ? true : false}>
            <Menu>
                <MenuButton as={Button} variant="unstyled">
                    {field.value ? (
                        <Flex align="center" gap={4}>
                            <Avatar size="sm" name={`${field.value.firstName} ${field.value.lastName}`} src={field.value.profilePictureUrl || undefined} />
                            <Text>{`${field.value.firstName} ${field.value.lastName}`}</Text>
                        </Flex>
                    ): (
                            <Flex align="center" gap={4}>
                                <Avatar size="sm" bg="gray.400" />
                                <Text>Unassigned</Text>
                            </Flex>
                    )}
                </MenuButton>

                <MenuList>
                    {filteredOptions.map((option) => (
                        <MenuItem key={option.email} onClick={() => handleSelectionChange(option)}>
                            <Flex align="center" gap={4}>
                                <Avatar name={`${option.firstName} ${option.lastName}`} src={option.profilePictureUrl || undefined} size="sm" />
                                <Text>{`${option.firstName} ${option.lastName}`}</Text>
                            </Flex>
                        </MenuItem>
                    ))}
                    {allowNull && (
                        <MenuItem key="Unassigned" onClick={() => handleSelectionChange(null)}>
                            <Flex align="center" gap={4}>
                                <Avatar size="sm" bg="gray.400" />
                                <Text>Unassigned</Text>
                            </Flex>
                        </MenuItem>
                    )}
                </MenuList>
            </Menu>
        </FormControl>
    )
}

Here is an example of one of the forms that I used this component in where I experience this issue

<Formik
    initialValues={{ assignee: ticketStore.selectedTicket!.assignee, error: null }}
    onSubmit={async (values, { setErrors }) => {
        try {
            await ticketStore.updateTicket(ticketStore.selectedTicket!.id, "assignee", values.assignee)
        } catch (error) {
            setErrors({ error: "Something went wrong. Please try again." })
        }
    }}
>
    {({ }) => (
        <Form>
            <UserDropdown name="assignee" options={projectStore.selectedProject!.users} allowNull submitOnSelect />
        </Form>
    )}
</Formik>

The objects that populate the list are ProjectParticipants

export interface ProjectParticipant {
    userId: string,
    projectId: string,
    email: string,
    firstName: string,
    lastName: string,
    profilePictureUrl: string | null,
    role: string
}

If a user with no profile picture is already selected as the initial value, then the background color shows up at first. But if you select a different user and then select the original user again, the background color suddenly shows up as white.

For reference, here is what the user avatar looks like as the initial value (This is what it's supposed to look like)

Good Avatar

And this is what it looks like when you select a different user and then reselect the original user

enter image description here

I know that using field.value with the useField hook provides a proxy object, and I'm not sure if using field.value.profilePictureUrl is the problem or how to get around that if it is the problem. Does anyone know what might be causing this behavior?


Solution

  • I fixed this issue by explicitly setting the Avatar's key property. The name property is what determines the background color of a Chakra avatar, and for some reason there was an issue with the way it was handling this. To get around this, I explicitly set the key property of each avatar to the name that was passed into it, and this fixed the issue.