Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use two svelte componenets on different pages with distinct ids?

I’d like to use two unrelated svelte compoents on two distincpages of a website say /cats and /dogs so in main.js I have

import App from './App.svelte'; //this is empty

import ListCats from './ListCats.svelte';

import ListDogs from './ListDogs.svelte';
 
new ListCats({
  target: document.querySelector('#list-cats'),
});

new ListDogs({
  target: document.querySelector('#list-dogs'),
});

const app = new App({
    target: document.body    
});

export default app;

The prblem is that error:

Uncaught Error: 'target' is a required option
    at new SvelteComponentDev (index.mjs:1993:19)
    at new ListDogs (ListDogs.svelte:76:39)
    at main.js:9:1
    at main.js:24:2

This arises becasue /cats page does not have #list-dogs and /dogs does not have #list-cats and both pages import the same bundle.js of svelte.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I avoid this problem?

>Solution :

try

let target = document.querySelector('#list-cats');
if (target) new ListCats({ target });

target = document.querySelector('#list-dogs');
if (target) new ListDogs({ target });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading