Creating Reusable Components
Sveip for å vise menyen
Reusable components are one of the most important ideas in modern frontend development. Instead of rebuilding the same interface multiple times, developers create flexible components that can be reused throughout an application.
This approach helps keep projects cleaner, faster to develop, and easier to maintain.
Why Reusable Components Matter
Imagine building an application with dozens of product cards, buttons, or profile sections. Creating separate HTML for every element would quickly become repetitive and difficult to manage.
Reusable components solve this problem by allowing developers to create a single component that can display different data using props.
This makes applications more scalable and organized.
Building a Reusable Button Component
Create a new file called Button.svelte inside the src folder.
Add the following code:
<script>
export let text = "Click Me";
</script>
<button>{text}</button>
<style>
button {
padding: 10px 18px;
border: none;
border-radius: 8px;
background-color: #7c3aed;
color: white;
cursor: pointer;
}
</style>
This component can now be reused anywhere in the application.
Using the Component Multiple Times
Open App.svelte and import the component:
<script>
import Button from './Button.svelte';
</script>
<Button text="Save" />
<Button text="Delete" />
<Button text="Continue" />
Even though all buttons use the same component, each one displays different content through props.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår