minidenticons icon indicating copy to clipboard operation
minidenticons copied to clipboard

Svelte component example

Open Joshimello opened this issue 10 months ago • 4 comments

Awesome library! Just wanted to share a component method for anyone using svelte :D Only the username prop is required.

Component:

<script lang="ts">
  import { minidenticon } from "minidenticons"

  export let username: string
  export let saturation: number = 95
  export let lightness: number = 45

  $: svgURI = 
    'data:image/svg+xml;utf8,' + 
    encodeURIComponent(minidenticon(username, saturation, lightness))
    
</script>

<img
  src={svgURI} 
  alt={username} 
  {...$$restProps}  
/>

Example usage with class props:

<Minidenticon username={USERNAME} class="h-12 w-12" />

Joshimello avatar Apr 22 '24 05:04 Joshimello

Thanks @Joshimello! I’d love to add your example to the readme, but if I’m right Svelte 5 will be released soon with the new "runes" syntax that makes $: svgURI = ... and other stuff obsolete. Last time I used Svelte it was still in version 3 so I’m not a Svelte expert :wink: Do you think you could rewrite your example with the new runes syntax?

laurentpayot avatar Apr 23 '24 07:04 laurentpayot

Sure! No problem!

Heres a typed version

<script lang="ts">
  import { minidenticon } from "minidenticons"

  let { 
    username,
    saturation = 95,
    lightness = 45,
    ...others
  } : {
    username: string,
    saturation?: number | string,
    lightness?: number | string,
    [key: string]: any
  } = $props()

  let svgURI: string = $derived(
    'data:image/svg+xml;utf8,' +
    encodeURIComponent(minidenticon(username, saturation, lightness))
  )

</script>

<img
  src={svgURI} 
  alt={username} 
  {...others}
/>

And an untyped version


<script>
  import { minidenticon } from "minidenticons"

  let { 
    username,
    saturation = 95,
    lightness = 45,
    ...others
  } = $props()

  let svgURI = $derived(
    'data:image/svg+xml;utf8,' +
    encodeURIComponent(minidenticon(username, saturation, lightness))
  )

</script>

<img
  src={svgURI} 
  alt={username} 
  {...others}
/>

Joshimello avatar Apr 23 '24 12:04 Joshimello

Thanks again @Joshimello :+1: I will probably add this in the docs in not too distant future. Hopefully before Svelte 6 is released :wink:

laurentpayot avatar Apr 26 '24 12:04 laurentpayot

Update: I’m actually waiting for React 19 to be officially released (not the beta) to revamp the docs.

laurentpayot avatar May 28 '24 12:05 laurentpayot