tjikko-studio / components

Component library for Tjikko Studio apps
0 stars 0 forks source link

More robust gallery and article #207

Closed shawninder closed 2 years ago

shawninder commented 2 years ago

@ktryndchrs does this look OK to you? Should allow for a more graceful behaviour when no images are passed into the Gallery component…

shawninder commented 2 years ago

@ktryndchrs Before you fixed the story, the gallery was completely broken and showing a huge red error because no images were provided and null.length isn't a thing (see line 40). So instead I'm using [] instead of null as a default value when no images are provided to allow the component to degrade more gracefully.

Basically, we had the equivalent of this:

interface Props {
  images?: string[] | null
}
function Component ({images = null}) {
  if (images.length) {
    return <p>We have {images.length} images</p>
  }
}

where the images prop is declared as optional but the component breaks if you don't provide it… So this:

  <Component />

breaks on if (images.length) because images is not an object and so we can't get its length property.

My version is more like this:

interface Props {
  images?: string[]
}
function Component ({images = [}) {
  if (images.length) {
    return <p>We have {images.length} images</p>
  }
}

So this:

<Component />

just renders this:

<p>We have 0 images</p>

instead of breaking.

Make sense?

ktryndchrs commented 2 years ago

Oh wow thanks for such a great explanation! @shawninder