Learn to Code via Tutorials on Repl.it!

← Back to all posts
Svelte Web Framework Tutorial #4 - Props
h
xfinnbar (149)

Requirements

For you to be able to follow along with this guide, you'll need to understand:

What are props?

Props are a way to pass data from one component to another. This data can be reactive.

Passing props

When we use a component, we can add the prop name as an attribute to pass some info to the component.

<ColoredButton color="green">Click here</ColoredButton>

Creating props for components

As an example, we'll be making a button with customizable colors.

First, I'll create the basic component and HTML structure.

src/pages/index.svelte:

<script>
import ColoredButton from  '../ColoredButton.svelte'
</script>

<ColoredButton color="green">Click here</ColoredButton>

src/ChangeColorButton.svelte:

<button><slot /><!-- Slot is the info between the tags. --></button>

Next, I'll add an a prop using export for the button, and add some CSS:

<script>
export let color = "red"; // Red is default,export declares a prop.
</script>
<button style="background-color: {color}"><slot /></button>

Now, it should be working. If you edit the color prop in src/pages/index.svelte, you should have a working, multicolored button.

Thanks for reading!

To be notified when the next tutorial is published, comment and I will mention you when the next one is out. Find any errors in this tutorial? Please tell me in the comments and I will do my best to fix them.

Comments
hotnewtop
EpicGamer007 (1755)

Hey rather than making a bunch of extremely short tutorials, maybe combine all your tutorials into one long one :)

xfinnbar (149)

@EpicGamer007 I will after I finish making all of them.

Bookie0 (6389)

@xfinnbar While you make them you don't have to post all the steps, just publish the final, big, result. :)

xfinnbar (149)

@Bookie0 I will combine them all into one post after they are all finished.

Bookie0 (6389)

Like I said you should post the finished result, not the steps @xfinnbar

EpicGamer007 (1755)

@xfinnbar what we are trying to say, is don't post every "part", combine all the parts into one. You can make the parts, but dont post them.

xfinnbar (149)

@EpicGamer007 I like to post them in parts so people who already know Svelte or need a reference can refresh their memory without having to sit through explanations for concepts they already understand.

EpicGamer007 (1755)

@xfinnbar is there something stopping you from writing a table of contents?