Web Components
Ursaciuc Adrian
Web components
Reusability
Get rid of duplicated code and make your application easier to maintain.
Custom elements
A set of JavaScript APIs that allow you to define custom elements and their behaviour.
Shadow DOM
A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element.
Web components
class MyComponent extends HTMLElement {
connectedCallback() {
this.innerHTML = `<h1>Hello world</h1>`;
}
}
customElements.define('my-component', MyComponent);
scripts.js
<my-component></my-component>
index.html
Let's code
Fake service
Fetch
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.
Promise/Async/Await
Promise
A promise is an operation that can eventually be completed.
Async
The word async before a function means one simple thing:
a function always returns a promise.
Await
The keyword await makes JavaScript wait until that promise settles and returns its result.
async function f() {
...
}
let response = await fetch('/articles.json');
How to use fetch
const response = await fetch("https://reqres.in/api/users");
const json = await response.json();
console.log(json);
Code
Result
{
data: Array(6) [
{ id: 1, email: "george.bluth@reqres.in", first_name: "George", … },
{ id: 2, email: "janet.weaver@reqres.in", first_name: "Janet", … },
{ id: 3, email: "emma.wong@reqres.in", first_name: "Emma", … },
...
],
page: 1,
per_page: 6,
total: 12,
total_pages: 2
}
Let's code
<script src="./scripts.js" type="module"></script>
Make it a module
CORS
Live Server
vs React
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor() {
super();
this.state = { data: [] };
}
async componentDidMount() {
const response = await fetch("https://reqres.in/api/users?per_page=10");
const json = await response.json();
this.setState({ data: json.data });
}
render() {
return (
<>
{this.state.data.map(user => (
<>
<div className="user-info">
<img src={user.avatar} alt="profile_pic" />
<h3>{user.first_name}</h3>
<span>{user.email}</span>
</div>
</>
))}
</>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Counter component
Call function inside component
this.parentElement.functionName()
Component life cycle
- connectedCallback - invoked when a component is inserted into the DOM
- disconnectedCallback - invoked when a component is removed from the DOM
Let's code again
Exercise
Make a component which will create other components
Thank you!
Github:
Web Components
By Ursaciuc Adrian
Web Components
- 465