Skip to content Skip to sidebar Skip to footer

Passing Props Down In Svelte

I'm trying to implement a fairly standard blog app using Svelte, Svelte Routing and Firestore, but I think I'm misunderstanding a fundamental part of how props are passed between c

Solution 1:

With svelte-routing, you don't pass props from the <Link> component, you pass them from the <Route> component implicitly. Where you have this...

<Routepath="posts/:id"component="{Post}" />

...you're telling the router that if the URL matches the pattern /posts/:id, it should render the Post component, passing it an id prop that matches that part of the URL.

The Post component is responsible for fetching its data based on that. So in this case, you could move the posts array into a separate module, and change Post.svelte accordingly:

<script>import posts from"./posts.js";

  exportlet id;
  $: post = posts.find(p => p.id == id);
</script><divclass="post"><h1>{ post.title }</h1><divclass="post-content">{ post.content }</div></div>

(Note that props are stringified because they're derived from the href, so we need a == comparison rather than ===.)

Here's a working fork.

Solution 2:

Simple example:

Parent Component

<script>importPostTeaserfrom"./PostTeaser.svelte";
  let post = {
    first: 'First prop',
    second: 'Second prop'
  };
</script><PostTeaser {...post} />

Child Component

<script>exportlet first;
    exportlet second;
</script>

First prop: {first} <br>
Second prop: {second}

Code here: https://codesandbox.io/s/spread-props-using-svelte-y7xou

Post a Comment for "Passing Props Down In Svelte"