Svelte conditional wrapper
Thu Mar 09 2023
I was adding an href
property to the Heading.svelte
component for this site and I encountered a familiar problem.
If the property was present, the whole component needed to be wrapped in an <a>
tag.
This might lead to something like this:
|
|
|
|
|
|
|
|
Obviously this isn't great. With React I would probably do something like this:
|
|
|
|
|
|
|
But that isn't great either. We could shorten it from 5 lines to 1 using a ternary operator but it might start to get unreadable. There's probably a more reusable React component or HOC that solves this but I haven't looked at this point.
Anyway, I found a Svelte repl with a neat idea which led to this component:
|
|
|
|
|
|
|
|
|
|
|
It uses <svelte:element>
to create whatever HTML tag name is passed to MaybeTag
.
We also pass any extra props to this element, and use <slot>
to forward the component's children.
Then we can rewrite the Heading
component like this:
|
|
|
|
Much cleaner.
We can also create a similar MaybeComponent
component using <svelte:component>
,
but I haven't actually used this yet.
|
|
|
|
|
|
|
|
|
|
|
Seemed useful enough to write it all down somewhere though. Thanks for reading :)