Last active
February 18, 2024 21:15
-
-
Save brandonros/959839445fb32bae75235d48cab466ec to your computer and use it in GitHub Desktop.
lit-element example with unpkg (no build), async API fetch() call, loading state, and styling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.0.0/custom-elements-es5-adapter.js"></script> | |
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.0.0/webcomponents-bundle.js"></script> | |
<script type="module"> | |
import { LitElement, css, html } from 'https://unpkg.com/lit-element@2.2.1/lit-element.js?module' | |
class SimpleGreeting extends LitElement { | |
static get styles() { | |
return css` | |
.color-red { color: red } | |
.color-blue { color: blue } | |
` | |
} | |
static get properties() { | |
return { | |
message: { type: String }, | |
class: { type: String } | |
} | |
} | |
async load() { | |
const response = await fetch('https://get.geojs.io/v1/ip/country.json?ip=8.8.8.8') | |
const responseBody = await response.json() | |
this.message = `Hello, ${responseBody[0].ip}!` | |
} | |
async connectedCallback() { | |
super.connectedCallback() | |
this.message = 'Loading...' | |
await this.load() | |
} | |
onClick() { | |
this.class = 'color-blue' | |
} | |
constructor() { | |
super() | |
this.message = '' | |
this.class = 'color-red' | |
this.addEventListener('click', this.onClick) | |
} | |
render() { | |
return html`<p class="${this.class}">${this.message}</p>` | |
} | |
} | |
window.customElements.define('simple-greeting', SimpleGreeting) | |
</script> | |
<title>LitElement Example</title> | |
</head> | |
<body> | |
<simple-greeting></simple-greeting> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can we pass the URL of API as parameter to this class, i tired adding public @Property() Url and did not work