Write simple, reusable HTML components in the style of React and Vue π
<script
defer
src="https://unpkg.com/fetch-components@latest/dist/render.min.js"
></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
renderHtml.renderComponent('card', '/components/card.html')
})
</script>
yarn add -D fetch-components
npm install -D fetch-components
import renderHtml from 'fetch-components'
document.addEventListener('DOMContentLoaded', () => {
renderHtml.renderComponent('card', '/components/card.html')
})
Create a HTML element with the data-render
attribute.
<div data-render="card"> </div>
This is the name of the component and is required when rendering.
Add the props you want to pass to the component via data-render-<prop>
attributes.
<div
data-render="card"
data-render-title="Get Started"
data-render-text="Join 1000+ happy customers"
data-render-href="/join"
>
</div>
Add the component file to the root of your project.
- builds
- src
- components
- card.html
Create the component HTML.
<a href="{{renderHref}}">
<h5>{{renderTitle}}</h5>
<p>{{renderText}}</p>
</a>
Note the lack of spacing between {{renderX}}
, that is required.
Render the HTML with the renderComponent
method, passing in the component
name and file.
document.addEventListener('DOMContentLoaded', () => {
renderHtml.renderComponent('card', '/components/card.html')
})
If you have nested components then you'll want to use the waitFor
function
that comes with the package.
<script>
document.addEventListener('DOMContentLoaded', () => {
renderHtml.renderComponent('parent', '/components/parent.html')
renderHtml.waitFor('parent').then(() => {
renderHtml.renderComponent('child', '/components/child.html')
renderHtml
.waitFor('child')
.then(() =>
renderHtml.renderComponent('subchild', '/components/subchild.html')
)
})
})
</script>
import renderHtml from 'fetch-components'
document.addEventListener('DOMContentLoaded', () => {
renderHtml.renderComponent('parent', '/components/parent.html')
renderHtml.waitFor('parent').then(() => {
renderHtml.renderComponent('child', '/components/child.html')
renderHtml
.waitFor('child')
.then(() =>
renderHtml.renderComponent('subchild', '/components/subchild.html')
)
})
})