Skip to content

Instantly share code, notes, and snippets.

@brandonros
Last active February 18, 2024 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonros/959839445fb32bae75235d48cab466ec to your computer and use it in GitHub Desktop.
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
<!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>
@bobmoss14
Copy link

How can we pass the URL of API as parameter to this class, i tired adding public @Property() Url and did not work

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment