cyyynthia / vite-plugin-magical-svg

An all-in-one Vite plugin that magically makes working with SVGs and bundling them a breeze.
BSD 3-Clause "New" or "Revised" License
45 stars 6 forks source link

Styling and classes? #3

Closed ricardo-valero closed 2 years ago

ricardo-valero commented 2 years ago

Don't know if this is in the project's scope, but how would someone style or animate an svg using this library?

Before I'd just import it and add a class

<MySvg className="myClassName"/>
cyyynthia commented 2 years ago

As this library transforms svg imports into a simple reference, styling is a bit more limited. If you treat your svg as a simple, 1-piece symbol, a className will still do the trick and allow for example changing its colors as usual (provided your svg' fill is currentColor). All the props passed to the component exposed by the lib (including refs) are forwarded to the svg element it creates.

Now if you do need a bit more advanced svg composition, or to animate only certain paths, for now the lib is a bit limited on this for the time being. You'd need to split the svg into pieces and the lib doesn't yet have the necessary stuff to do so.

What's your specific use-case?

ricardo-valero commented 2 years ago

I have a svg with a simple animation

https://codepen.io/RicardoValero/pen/xxPavoa

.dash > path {
  stroke-dasharray: 10;
  stroke-dashoffset: 1000;
  animation: dash 3s alternate infinite;
}

@keyframes dash {
  0% {
    stroke-dashoffset: 0;
    stroke-dasharray: 2;
  100% {
    stroke-dashoffset: 1000;
    stroke-dasharray: 500;
  }
}
cyyynthia commented 2 years ago

Alright, then for you case you simply need to target use instead of path and you'll be good to go:

When doing

import DashSvg from '...'

export default function () {
  return (
    <div>
      <DashSvg className='dash'/>
    </div>
  )
}

The result to expect is something like this:

<div>
  <svg ... class='dash'>
    <use href='/assets/sprite.xxxxxxx.svg#xxxxxx'/>
  </svg>
</div>

Therefore, animating the \ (or even just the \ element itself) will work as expected

ricardo-valero commented 2 years ago

Thank you :D