This video is available to students only

How to Clean Up and Componentize Svelte Code

Componentizing our code for a more readable project


Our scrollytelling project is now complete! But we can make our codebase a bit cleaner with some componentization. Our App.svelte file has a lot going on, and we can make it more readable by breaking it up into smaller components. (Note that this is technically optional, as our project is working; but its good practice to make our code as readable as possible.)

Let's identify what's happening in App.svelte, so we can see what we can break out into components.

  1. Initial chart logic, rendering, and style

  2. Scroll handling and step rendering

  3. Hover logic and rendering

Let's split up our code into these three sections. We'll start by moving the initial chart logic into a new component, Chart.svelte.

1. Initial chart logic, rendering, and style#

We'll start by moving the initial chart logic into a new component, Chart.svelte.

Go ahead and copy your .sticky div (and everything within) to this new file.

This component will need all chart-related code passed as props. The easiest way to find the needed props is to paste in our markup, and see what the compiler complains is missing.

Handle these one by one, by passing in the missing variable as a prop.

The tricky part here is that some props are read-only, meaning they don't need to be changed by the component. But others need to pass information back up to the parent component (child-to-parent communication). These variables include anything that we "set" or otherwise modify in Chart.svelte: width, height, and hoveredData. In order to update those in App.svelte, we'll add the following syntax in the component markup:

So in our case, our Chart.svelte markup will look like this:

This lesson preview is part of the Better Data Visualizations with Svelte course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to Better Data Visualizations with Svelte, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Better Data Visualizations with Svelte