DEV Community

Cover image for Svelte Components
Arya Krishna
Arya Krishna

Posted on

Svelte Components

*What is a component? *

A component in simple words is a stand alone section of a webpage. Basically they are the building blocks to create a web page which can be put together and output to the dom or the browser to create a whole website.

For example the nav baror footer on your webpage can be a component. In svelte kit whole page is represented by component as well. Say for example you have an about page, then in order to represent that about page you would have an about component also. Naming of a svelte component has to be something.svelte, for example for an about page it can beabout.svelte. That means the .svelteextension is being used in naming svelte components.

Inside a svelte component we can essentially have 3 different things -

  1. an html template- which is the html page that is rendered to the browser.
  2. a script tag - where any interactive javascript which we inject in to the webpage goes in.
  3. a style tag- where any css to style the template goes in.

We usually write all of our svelte code inside the src folder. We create the components and later inject them into the dom. All of our scripts from our different components and all of our styling from the components are bundled together and made in to a single file in svelte.

let name = 'Arya';

<h1> hello {name}</h1>
Enter fullscreen mode Exit fullscreen mode

The code block above explains the syntax in which we dynamically write svelte.

Binding variables or values to input fields -

<input type = "text" bind:value = " "  >
Enter fullscreen mode Exit fullscreen mode

In order to bind a variable or value to input fields, all we have to do is add and input type text and add in a bind attribute : and add what we would like to bind to the value of the input.

What this help us achieve is that when the value of the input changes, then the variable changes accordingly and vice versa.

Discussion (1)

tzwel profile image

i can just head straight to the docs and read the same, and try it out instantly using the interactive REPL