javascript / intermediate
Snippet
Dynamic Component Rendering
The <svelte:component> element allows you to dynamically render a component based on an expression. This is useful for building dashboards, tab systems, or any UI where the specific component to be displayed isn't known until runtime.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>import LineChart from './LineChart.svelte';import BarChart from './BarChart.svelte';let chartType = 'line';const chartMap = { line: LineChart, bar: BarChart };</script><select bind:value={chartType}><option value="line">Line</option><option value="bar">Bar</option></select><svelte:component this={chartMap[chartType]} data={analytics} />
svelte
Breakdown
1
const chartMap = { line: LineChart, bar: BarChart };
Stores the component constructors in an object for easy lookup.
2
<svelte:component this={...} />
A special Svelte element that instantiates the component passed to the 'this' property.