Can you create reusable components in html? Let's say I want to encapsulate some css / html and js into a tidy reusable component. How do web developers do this? I'm coming from the Flex, C# side of the planet.
In React, a reusable component is a piece of UI that can be used in various parts of an application to build more than one UI instance. For instance, we can have a Button component that displays different texts on different pages.
An HTML element is defined by a start tag, some content, and an end tag.
Having reusable common components has advantages like,Low learning curve. Consistency across the ecosystem - with re-usable components user-experience will be same across all the products. Easy to maintain the products - any issue with component found in one product would be fixed automatically for all the products.
This question is 7 years old and a lot has changed since. Web components and are now implemented or can be used with polyfills in every major browser. Which means you can use Polymer by Google or X-Tag supported by Microsoft made exactly for this.
<dom-module id="custom-tag">
<template>
<style>
h1 {
color: red;
}
</style>
<div class="text-holder">
<h1>[[name]]</h1>
<p>[[description]]</p>
</div>
</template>
</dom-module>
<script>
Polymer({
is: "custom-tag",
properties: {
name: String,
description: String
}
});
</script>
include tag in head:
<link rel="import" href="path/to/custom-tag.html"/>
and then:
<custom-tag
name="Lorem"
description="Lorem ipsum dolor sit amet.">
</custom-tag>
You'll need a simple http server because of the html import. Encapsulation you talked about is backed by Shadow DOM - javascript and css packed inside of custom tag won't "bleed out" and change anything outside of the element and vice versa (unless you force it). Polymer comes out with quite large asset of elements, you can find it here.
Everything about using elements and creating your own is covered here.
You can use Server-Side Includes to directly import pieces of HTML (e.g. a header), but most frameworks these days tend to approach things at a higher level, e.g. Apache Taglibs or Django templates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With