Live editing with Svelte

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 Live Editing

  •  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
npm i @cloudcannon/svelte-connector

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

index.svelte
"};
<script>
  import { onDestroy, onMount } from 'svelte';
  import { onCloudCannonChanges, stopCloudCannonChanges } from '$lib/cloudcannon.js';
  
  // 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.

Was this article helpful? or Suggest an improvement >

Related articles

Other Resources

  1. @cloudcannon/svelte-connector
  2. GitHub