Visual data previews with Svelte

Last modified: January 10th, 2024

Svelte is great at receiving new data and rerendering components. To make this integration work we hook into the Svelte lifecycle. onMount and onDestroy can set up event listeners that update the pages properties.

Requirements for data previews#

  • Components must have an output URL. SvelteKit routes are a good example.
  • Components must get their data from a data/content file somewhere in your project. This is critical, as the Visual Editor cannot open the components themselves.
  • These data/content files must be configured as a CloudCannon Collection. See the CloudCannon Reader documentation for more information.
  • Components will need to use the Svelte onDestroy and onMount functions.

Installation and Usage#

The CloudCannon Svelte connector is available on npm.

To install, run:

Shell
copied
npm i @cloudcannon/svelte-connector

Next, add the following code to any component that you want to add live editing to:

index.svelte
copied
<script>
  import { onDestroy, onMount } from 'svelte';
  import { onCloudCannonChanges, stopCloudCannonChanges } from '@cloudcannon/svelte-connector';

  // pageDetails is passed from parent, or via SvelteKit load function
  export let pageDetails;

  onMount(async () => {
    onCloudCannonChanges((newProps) => pageDetails = newProps);
  });

  onDestroy(async () => {
    stopCloudCannonChanges();
  });
</script>

In the above code, pageDetails is an object that contains data for the markup portion of the component.

After loading the content file in the Visual Editor, changing the data in the sidebar will push the new props to pageDetails. This will display the new values in the Visual Editor immediately.

This should make no difference to your development or production environment.

For an example integration, check out our Urban SvelteKit template. If you have any issues, please contact support, or raise an issue on the GitHub repository.

Related Articles

Related links

Open in a new tab