question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItĀ collects links to all the places you might be looking at while hunting down a tough bug.

And, if youā€™re still stuck at the end, weā€™re happy to hop on a call to see how we can help out.

Problems with <Image /> component

See original GitHub issue

First off, thank you for an awesome library. I hope this is one the community can support šŸš€. Iā€™m running into several problems with the <Image /> component which Iā€™ll outline below.

Problem 1 - <img /> width / height props

HTML <img /> accepts width / height attributes which helps the browser paint the screen without ā€œjankā€. Currently, <Box> / styled-system / ?, takes these props as css width/height. I understand that this is intentional and desirable for most situations. Perhaps we could add htmlWidth and htmlHeight (similar to htmlFor from react-dom) and pass those props as to the underlying <img /> element.

Proposed prop names:

  1. htmlWidth / htmlHeight
  2. widthAttribute / heightAttribute
  3. domWidth / domHeight

Whatever you decide here, keep in mind that there will likely be other prop names that should pass through to the underlying element in the future.

Problem 2 - useImageHasLoaded hook causing multiple network requests

The useHasImageLoaded causes (I think) multiple network requests for the same image. I have not tested with the optional fallbackSrc, but this should not be required for proper image loading.

Problem 3 - <Box /> and BoxProps TypeScript

I attempted to workaround Problem 1 & 2 in my user code by reimplementing <Image>. I, too, would like to do so using <Box as="img" ... /> similarly to how this lib handles it. The problem I encountered immediately is BoxProps. The TypeScript types are defined as such that <Box as="img" /> doesnā€™t accept a src prop. This is likely going to be a problem for many TypeScript users that would like use the <Box as="something" /> paradigm. Iā€™m not sure if this can be solved generically by the lib. Also, Iā€™m not sure how to solve this in my own code yet. It may be unfortunate to have to resort to allowing every possible prop such as src on <Box /> just because it may be used as an <img />, <video />, or <SomeRandomComponent />.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:3
  • Comments:17 (9 by maintainers)

github_iconTop GitHub Comments

4reactions
segunadebayocommented, Oct 16, 2019

@paynecodes, yep. Itā€™s live already, check here: https://chakra-ui.com/image#props

Currently working on the Typescript issue.

2reactions
mshwerycommented, Sep 14, 2021

hereā€™s a sample of the code (missing a couple functions but you can fill in the blanks). Like I mentioned, we basically rewrote the Avatar so it wouldnā€™t have the flashing behavior at all, because there is no way around it when using the Chakra Avatar.

export default React.forwardRef((props: AvatarProps, ref: React.ForwardedRef<HTMLDivElement>) => {
  const { name, size = 'md', src, ...boxProps } = props

  const [imageUnavailable, setImageUnavailable] = React.useState(!src)

  usePreloadedImage(src)

  const initials = React.useMemo(() => getInitials(name), [name])
  const hash = React.useMemo(() => hashCode(name), [name])
  const theme = useTheme()

  const bgColorKeys = Object.keys(theme.colors).filter((key) => {
    return !['black', 'transparent', 'current', 'white', 'whiteAlpha', 'blackAlpha'].includes(key)
  })

  const backgroundColor = name ? theme.colors[bgColorKeys[hash % bgColorKeys.length]]['100'] : theme.colors.gray['300']

  const color = readableColor(backgroundColor) === '#000' ? 'gray.900' : 'white'

  const resolvedSize = getSize(size)

  return (
    <Flex
      ref={ref}
      flex="none"
      position="relative"
      display="flex"
      justifyContent="center"
      alignItems="center"
      boxSize={resolvedSize}
      borderRadius="100%"
      color={color}
      backgroundColor={backgroundColor}
      {...boxProps}
    >
      {imageUnavailable && (
        <Text
          color="inherit"
          opacity={0.9}
          fontSize={Math.floor(parseInt(resolvedSize as string, 10) / 2)}
          fontWeight="500"
        >
          {initials}
        </Text>
      )}
      {!imageUnavailable && (
        <Img
          objectFit="cover"
          width="100%"
          height="100%"
          borderRadius="100%"
          overflow="hidden"
          src={src}
          onError={() => setImageUnavailable(true)}
        />
      )}
    </Flex>
  )
})
Read more comments on GitHub >

github_iconTop Results From Across the Web

Issues with new next/image component #18476 - GitHub
Issue 1: Make a list that has images; create an action that replaces the content & images with new content & images, like...
Read more >
Building an effective Image Component - Chrome Developers
An image component encapsulates performance best practices and provides an out-of-the-box solution to optimize images.
Read more >
Fix Layout Shifts with Image Component - Media Jams
Images are one of the major causes of layout shift, and one way to avoid this is to specify the width and height...
Read more >
You're Doing Image Rendering WRONG in Next.js! - YouTube
Want coding problems (with solutions!) delivered to your inbox daily!? ... the Next.js Image Component 07:23 Comparing JPEG and WEBP images ...
Read more >
Fix Broken Images in React with Next.js - YouTube
Learn how to create a simple fallback image component for missing or broken images using React and Next.js.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found