Svelte 3 components - In Detail

Svelte 3 components - In Detail

In our previous articles, we learn about creating the components and pass properties to the components. However, there are a lot more things it does in a web app. We discuss it in detail in this article.

As we already know that in Svelte .sveltefiles are components. These files have

  • JavaScript (logic)
  • HTML
  • CSS

Like other frameworks, Components are

  • Fundamental building blocks of web applications in Svelte.
  • Reusable and used in different parts of the application.
  • Accepts data from other components
  • Contains logic for the application

In the previous article, we render components

<FirstComponent firstName={"Michael"} lastName={"Foo"} />

Above, we pass data as Props, but we can also use the children components to pass data. Children provide content to the parent component. It can be

  • Text
  • HTML
  • Svelte components

Example of props

<script>
	import FirstComponent from './FirstComponent.svelte';
	let user_id = 2;
</script>

<FirstComponent 
    firstName={"Michael"} 
    lastName={"Foo"} 
    is_admin={true}
    email={getEmail(user_id)}
 />

getEmail is the function.

Components Name

Inside Svelte components, there is no class, function name, or property value defined. Unlike other frameworks, the name of the file file_name.svelte is imported.

Components imports other components inside their script element:

import FirstComponent from './FirstComponent.svelte';

And the imported components are used as:

<FirstComponent />

Component names must start with uppercase and may consist of multiple words (camel-cased). Lowercase names reserves for predefined elements like those provided by HTML and SVG. Though not required, component names match the name of their source file.

import FirstComponent from './FirstComponent.svelte';
import Second from './FirstComponent.svelte';

// Both the statements are valid. But only use one at a time

Scoped vs. global styles

Global styles are desirable when uniform CSS requires across all components. For example, the color of buttons, the header should be uniform across the application.

Scoped styles are for styling the elements within a component and not affecting other parts of the app.

The CSS specified in a Svelte component are scoped in nature. To define global properties in Svelte component

<h1> Hello there, I am global </h1>

<style>
    .override :global(h1) {
    	color: blue;
    }
</style>

Component State

State is plain JavaScript object. These objects are managed within the components. Components managed its own state. It is not changed by the Parent and a component cannot changed the state of its child components.

<script>
	let variable1 = 0;
    variable1++;
</script>

<div> Variable Value : {variable1++} </div>

Whenever the page is refresh or loaded again the variable1 value resets to 0;

Thats all about components. Subscribe or follow me to get the notifications of my next article.