'Hide Svelte component from outside script
I am importing a third-party Svelte3 component with several children. For the sake of example, the third-party component looks like the following:
<script>
import Child1 from './third-party/Child1.svelte';
import Child2 from './third-party/Child2.svelte';
</script>
<div>
<Child1/>
<Child2/>
</div>
What would be the cleanest way to hide one of the children components from within my app (or from the dev console) given that:
- it has no easily identifiable CSS selector, and
- I cannot modify the third-party code?
In Vue, I would use the root instance, but is this possible in Svelte?
Thank you very much!
Guido
Solution 1:[1]
There is no clean way. Messing with the DOM from outside a component is a hacky solution and can lead to unpredictable results.
This is a feature the third party needs to add to their public api.
An option for the third party is to expose the feature is via props using $set using the component api:
// App.svelte
<script>
import Child1 from './third-party/Child1.svelte';
import Child2 from './third-party/Child2.svelte';
export let child2Visible = true;
</script>
<div>
<Child1/>
{#if child2Visible}
<Child2/>
{/if}
</div>
// my-app.js
import App from "./App.svelte";
window.app = new App({target});
// From dev console
app.$set({ child2Visible: false })
Another way for the third party is to expose a way for setting a store value which could toggle some of the ui.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bob Fanger |