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.
Initial chart logic, rendering, and style
Scroll handling and step rendering
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.
xxxxxxxxxx
<script>
export let width;
export let height;
export let currentStep;
export let hoveredData;
export let margin;
export let innerWidth;
export let innerHeight;
export let yScale;
export let xScale;
export let renderedData;
export let radius;
</script>
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:
xxxxxxxxxx
<Component bind:variable={variable} />
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.
Get unlimited access to Better Data Visualizations with Svelte, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
