Motion
A motion replacement for any DOM element can be generated with this syntax:
<script>
import { M } from 'svelte-motion'
</script>
<M.h1>A big motion header</M.h1>
<M.div>A big motion header</M.h1>
<M.button>A motion button</M.button>
This way you can quickly add motion to your page. Any prop you pass is either used by the Motion
or forwarded to the underlying DOM element.
One drawback of this syntax is, that you loose direct access to the DOM element. Eg. for the M.button
above, you can use Svelte-Motions tap
callback, but you can’t use the on:click
directive. If you need or want access to the DOM element, to use events, class:
directive, actions or other reasons, you can use the Motion
component:
<script>
import { Motion } from 'svelte-motion'
</script>
<Motion let:motion><h1 use:motion>A big motion header</h1></Motion>
<Motion let:motion><div use:motion>A big motion header</div></Motion>
<Motion let:motion><button use:motion>A motion button</button></Motion>
The Motion
component exposes an action motion
via slot props, so you access it with the let:
directive. This action is applied to the DOM element, which you want to animate.
SVG elements
If you want to animate SVG elements, like circle
, g
and path
, you need to add true
to the isSVG
prop of the Motion
component. If you use the M
component, this is done automatically:
<script>
import { M, Motion } from 'svelte-motion'
</script>
<svg>
<!-- M handles svg automatically -->
<M.path />
<Motion let:motion>
<circle use:motion/>
</Motion>
</svg>
Custom Motion DOM elements
If you as an example want to animate several buttons and need access to the on:click
directive, it might be worthwhile to generate a MotionButton
component, which forwards the events you need:
<script>
// MotionButton.svelte
import Motion from "svelte-motion";
</script>
<Motion {...$$restProps} let:motion let:props>
<button {...props} use:motion on:click><slot/></button>
</Motion>
All unused props are passed from the Motion
component down to the button via slot props. This way you don’t need to export props.
If you need several MotionH1
s or MotionDiv
s or a different tag, I encourage you to use the pattern above to generate them yourself in your project.