This site is dedicated to all things I see and that I think are interesting to publish almost always are other very smart people.

My Little Pictures

A Guide to Custom Elements for React Developers

CSS-Tricks by Charles Peters

I had to build a UI recently and (for the first time in a long while) I didn’t have the option of using React.js, which is my preferred solution for UI these days. So, I looked at what the built-in browser APIs had to offer and saw that using custom elements (aka Web Components) may just be the remedy that this React developer needed.

Custom elements can offer the same general benefits of React components without being tied to a specific framework implementation. A custom element gives us a new HTML tag that we can programmatically control through a native browser API.

Let’s talk about the benefits of component-based UI:

  • Encapsulation – concerns scoped to that component remain in that component’s implementation
  • Reusability – when the UI is separated into more generic pieces, they’re easier to break into patterns that you’re more likely to repeat
  • Isolation – because components are designed to be encapsulated and with that, you get the added benefit of isolation, which allows you scope bugs and changes to a particular part of your application easier

Use cases

You might be wondering who is using custom elements in production. Notably:

  • GitHub is using custom elements for their modal dialogs, autocomplete and display time.
  • YouTube’s new web app is built with Polymer and web components.

Similarities to the Component API

When trying to compare React Components versus custom elements, I found the APIs really similar:

  • They’re both classes that aren’t “new” and are able that extend a base class
  • They both inherit a mounting or rendering lifecycle
  • They both take static or dynamic input via props or attributes

Demo

So, let’s build a tiny application that lists details about a GitHub repository.

If I were going to approach this with React, I would define a simple component like this:

<Repository name="charliewilco/obsidian" />

This component takes a single prop — the name of the repository — and we implement it like this:

class Repository extends React.Component {
  state = {
    repo: null
  };

  async getDetails(name) {
    return await fetch(`https://api.github.com/repos/${name}`, {
      mode: 'cors'
    }).then(res => res.json());
  }

  async componentDidMount() {
    const { name } = this.props;
    const repo = await this.getDetails(name);
    this.setState({ repo });
  }

  render() {
    const { repo } = this.state;

    if (!repo) {
      return <h1>Loading</h1>;
    }

    if (repo.message) {
      return 
Error: {repo.message}
; } return (

{repo.full_name}

{repo.description}
); } }

See the Pen React Demo – GitHub by Charles (@charliewilco) on CodePen.

To break this down further, we have a component that has its own state, which is the repo details. Initially, we set it to be null because we don’t have any of that data yet, so we’ll have a loading indicator while the data is fetched.

During the React lifecycle, we’ll use fetch to go get the data from GitHub, set up the card, and trigger a re-render with setState() after we get the data back. All of these different states the UI takes are represented in the render() method.

Defining / Using a Custom Element

Doing this with custom elements is a little different. Like the React component, our custom element will take a single attribute — again, the name of the repository — and manage its own state.

Our element will look like this:

<github-repo name="charliewilco/obsidian"></github-repo>
<github-repo name="charliewilco/level.css"></github-repo>
<github-repo name="charliewilco/react-branches"></github-repo>
<github-repo name="charliewilco/react-gluejar"></github-repo>
<github-repo name="charliewilco/dotfiles"></github-repo>

See the Pen Custom Elements Demo – GitHub by Charles (@charliewilco) on CodePen.

To start, all we need to do to define and register a custom element is create a class that extends the HTMLElement class and then register the name of the element with customElements.define().

class OurCustomElement extends HTMLElement {}
window.customElements.define('our-element', OurCustomElement);

And we can call it:

<our-element></our-element>

This new element isn’t very useful, but with custom elements, we get three methods to expand the functionality of this element. These are almost analogous to React’s lifecycle methods for their Component API. The two lifecycle-like methods most relevant to us are the disconnectedCallBack and the connectedCallback and since this is a class, it comes with a constructor.

Name Called when
constructor An instance of the element is created or upgraded. Useful for initializing state, settings up event listeners, or creating Shadow DOM. See the spec for restrictions on what you can do in the constructor.
connectedCallback The element is inserted into the DOM. Useful for running setup code, such as fetching resources or rendering UI. Generally, you should try to delay work until this time
disconnectedCallback When the element is removed from the DOM. Useful for running clean-up code.

To implement our custom element, we’ll create the class and set up some attributes related to that UI:

class Repository extends HTMLElement {
  constructor() {
    super();

    this.repoDetails = null;

    this.name = this.getAttribute("name");
    this.endpoint = `https://api.github.com/repos/${this.name}`    
    this.innerHTML = `<h1>Loading</h1>`
  }
}

By calling super() in our constructor, the context of this is the element itself and all the DOM manipulation APIs can be used. So far, we’ve set the default repository details to null, gotten the repo name from element’s attribute, created an endpoint to call so we don’t have to define it later and, most importantly, set the initial HTML to be a loading indicator.

In order to get the details about that element’s repository, we’re going to need to make a request to GitHub’s API. We’ll use fetch and, since that’s Promise-based, we’ll use async and await to make our code more readable. You can learn more about the async/await keywords here and more about the browser’s fetch API here. You can also tweet at me to find out whether I prefer it to the Axios library. (Hint, it depends if I had tea or coffee with my breakfast.)

Now, let’s add a method to this class to ask GitHub for details about the repository.

class Repository extends HTMLElement {
  constructor() {
    // ...
  }

  async getDetails() {
    return await fetch(this.endpoint, { mode: "cors" }).then(res => res.json());
  }
}

Next, let’s use the connectedCallback method and the Shadow DOM to use the return value from this method. Using this method will do something similar as when we called Repository.componentDidMount() in the React example. Instead, we’ll override the null value we initially gave this.repoDetails — we’ll use this later when we start to call the template to create the HTML.

class Repository extends HTMLElement {
  constructor() {
    // ...
  }

  async getDetails() {
    // ...
  }

  async connectedCallback() {
    let repo = await this.getDetails();
    this.repoDetails = repo;
    this.initShadowDOM();
  }

  initShadowDOM() {
    let shadowRoot = this.attachShadow({ mode: "open" });
    shadowRoot.innerHTML = this.template;
  }
}

You’ll notice that we’re calling methods related to the Shadow DOM. Besides being a rejected title for a Marvel movie, the Shadow DOM has its own rich API worth looking into. For our purposes, though, it’s going to abstract the implementation of adding innerHTML to the element.

Now we’re assigning the innerHTML to be equal to the value of this.template. Let’s define that now:

class Repository extends HTMLElement {
  get template() {
    const repo = this.repoDetails;
  
    // if we get an error message let's show that back to the user
    if (repo.message) {
      return `
Error: ${repo.message}
` } else { return `

${repo.full_name}

${repo.description}
` } } }

That’s pretty much it. We’ve defined a custom element that manages its own state, fetches its own data, and reflects that state back to the user while giving us an HTML element to use in our application.

After going through this exercise, I found that the only required dependency for custom elements is the browser’s native APIs rather than a framework to additionally parse and execute. This makes for a more portable and reusable solution with similar APIs to the frameworks you already love and use to make your living.

There are drawbacks of using this approach, of course. We’re talking about various browser support issues and some lack of consistency. Plus, working with DOM manipulation APIs can be very confusing. Sometimes they are assignments. Sometimes they are functions. Sometimes those functions take a callback and sometimes they don’t. If you don’t believe me, take a look at adding a class to an HTML element created via document.createElement(), which is one of the top five reasons to use React. The basic implementation isn’t that complicated but it is inconsistent with other similar document methods.

The real question is: does it even out in the wash? Maybe. React is still pretty good at the things it’s designed to be very very good at: the virtual DOM, managing application state, encapsulation, and passing data down the tree. There’s next to no incentive to use custom elements inside that framework. Custom elements, on the other hand, are simply available by virtue of building an application for the browser.

Learn more

The post A Guide to Custom Elements for React Developers appeared first on CSS-Tricks.


Noteplan – Markdown Calendar, Todos, and Notes

Comments

Memorable Memorials: 10 Extraordinary War Monuments

[ By Steve in Culture & History & Travel. ]

These extraordinary war monuments stand out from the crowd in commemorating those who have fallen while performing their duty in the service of their country.

Memorial Day was formerly known as “Decoration Day” and was traditionally celebrated on May 30th – a date upon which no major battles had been fought. Memorial Day differs from Veterans Day in that the latter honors veterans of war. We lead off with a unique war memorial designed to fulfill its mission, as it were, on only one day every year: November 11th, at 11:11am, no less. The Anthem Veterans Memorial in suburban Phoenix, Arizona, was dedicated in 2012. The monument’s white stones, red bricks and blue sky reflect the colors of the American flag.

The Anthem Veterans Memorial consists of five staggered stone pillars signifying the five branches of the United States military. Designer Renee Palmer-Jones precisely aligned the pillars so that at 11:11am on November 11th, the sun’s rays pass through elliptical cutouts in the five pillars. The sunlight spotlights a mosaic of The Great Seal of the United States set into the red-bricked Circle of Honor.

Soldierstone Memorial

Most people have neither seen nor even heard of Soldierstone… and that’s just as the memorial’s creator, the late Stuart Allen Beckley, intended. The retired Army lieutenant colonel and Vietnam veteran sought to pay tribute to the uncredited people who assisted foreign soldiers over many decades of war in Southeast Asia.

Secreted in a clearing deep in Colorado’s 1.8-million-acre Rio Grande National Forest at 10,000 feet above sea level, Soldierstone‘s central 10-ft-tall monument bears quotes engraved in Vietnamese, Laotian, Cambodian and French – the languages of America’s allies through thirty years of fighting. Flickr user MJM1977visited the memorial on July 24th of 2014.

Polar Bear Monument

The Polar Bear Monument in Troy, Michigan, commemorates fallen soldiers of the North Russian Expeditionary Forces. About 75 percent of the 5,500 Americans sent to Archangel, Russia as part of the post-WWI Allied Intervention were from the Detroit area and called themselves the “Polar Bears”.

96 soldiers were KIA in Russia and in 1929; the remains of 56 were recovered and subsequently interred on this site on May 30th of 1930. Flickr user Jazz Guy (flickr4jazz) visited the Polar Bear Memorial on May 2nd, 2011.

Next Page – Click Below to Read More:
Memorable Memorials 10 Extraordinary War Monuments

[ By Steve in Culture & History & Travel. ]

[ WebUrbanist | Archives | Galleries | Privacy | TOS ]


Breathing Earth of vegetation

Flowing Data

Using data from NOAA STAR, Nadieh Bremer creates a breathing Earth that shows the seasonal cycles of vegetation over the course of a year.

The animation happening in the map above, through all 52 weeks of 2016, visualizes these seasonal cycles. The rise and fall of the growing season in the Northern Hemisphere is particularly visible. However, when focusing on different parts of the planet other cycles & different seasons become noticeable as well; the Southern regions of Africa, Brazil, and New Zealand, having the reverse cycle as the North, or India getting drier and drier up until the July when the monsoons start. The more often you watch the year go by, the more small details will start to stand out.

See also John Nelson’s project from a while back of the same name, which made use of satellite imagery.

Tags: animation, environment, vegetation


¿Esta píldora te evitará ir al gimnasio?

Genciencia by Sergio Parra

Si el olor de los gimnasios te repele, si no quieres compartir espacio vital con los que suelen retorcer mancuernas para, a continuación, avanzabar en esa actitud chulesca que recuerda de perfil a un croissant, o sencillamente hacer deporte te da pereza, quizá esta píldora podría ser la solución a todos tus males.

En definitiva, una pastilla que produce los beneficios del ejercicio físico ahorrándonos los sacrificios que acarrea.

El desarrollo de la píldora

Esta pastilla no era un mito, sino una idea conceptual basada en un desarrollo de investigadores del Instituto Salk, en La Jolla (California), que creen que sería posible de concebirla.

Con todo, si ya estás empezando a dar palmadas de alegría, mejor que te advierta que: a) todavía queda trabajo para terminarla y b) no se usará para los perezosos, sino para personas con trastornos cardiacos o pulmonares, discapacitados o afectados por la diabetes tipo 2.

El secreto reside en el hallazgo de un gen en ratones, el el PPARD, que causa los mismos efectos que el entrenamiento físico: no ganaban peso con facilidad y tenían una respuesta rápida a la insulina.

Los investigadores han encontrado también un compuesto químico, llamado GW1516, que activaba el gen PPARD.

Tras el análisis molecular de los músculos de ratones que habían recibido este compuesto duarante ocho semanas, se descubrió que cambiaba la expresión de 975 genes: los que se activaban estaban vinculados a la quema de grasa para conseguir energía, mientras que los se apagaban eran los encargados de hacer lo propio con los carbohidratos (azúcares). Según explica Michael Downes, coautor del estudio:

El estudio sugiere que quemar grasa no es tanto una manera de lograr la resistencia cardiovascular, sino más bien de ahorrar glucosa y preservar el buen funcionamiento del cerebro.

El siguiente paso potencial sería la creación de un medicamento para humanos basado en el compuesto GW1516 que pueda activar el gen PPARD sin necesidad de hacer ejercicio a fin de ayudar a personas con trastornos cardiacos o pulmonares, discapacitados o afectados por la diabetes tipo 2.


Poly Fluid Sizing

Jake Wilson digs in, and while he finds that calc() isn’t quite up for the job (e.g. font-size: calc(3vw * 3vw); /* This doesn't work in CSS */), he does land on a technique he’s calling Poly Fluid Sizing, which takes a map of breakpoints and font sizes and linear interpolates them just about as good (*it depends*).

Direct Link to ArticlePermalink

Poly Fluid Sizing is a post from CSS-Tricks


Air Tight Bonsai AL-05 Mini-Monitor

The Absolute Sound Articles

Air Tight Bonsai AL-05 Mini-MonitorIf you think mini-monitor means small sound, the Air Tight Bonsai will have you thinking again. Forget mini; the sound here is decidedly, uh, maxi. For starters, the speaker’s wide dispersion and voluptuously full and rounded imaging will fool you into thinking you’re listening to a far larger transducer. Plus, in the midband the Bonsai delivers an exciting sense of immediacy and a bold presence, coupled with remarkable detail, that also belie its size and single 4″ driver. It’s a thing of beauty to behold, to boot. Air Tight, founded by the legendary Atsushi Miura and based outside of Osaka, …

 


Discover “Unpaywall,” a New (and Legal) Browser Extension That Lets You Read Millions of Science Articles Normally Locked Up Behind Paywalls

Open Culture

Earlier this month, Impactstory, a nonprofit supported by grants from the National Science Foundation and the Alfred P. Sloan Foundation, launched, Unpaywall, a free browser extension that helps you “find open-access versions of paywalled research papers, instantly.”

As the co-founders of Impactstory describe itUnpaywall is “an extension for Chrome and Firefox that links you to free full-text as you browse research articles. Hit a paywall? No problem: click the green tab and read it free!”

Their FAQ gets into the mechanics a little more, but here’s the gist of how it works: “When you view a paywalled research article, Unpaywall automatically looks for a copy in our index of over 10 million free, legal fulltext PDFs. If we find one, click the green tab to read the article.”

While many science publishers put a paywall in front of scientific articles, it’s often the case that these articles have been published elsewhere in an open format. “More and more funders and universities are requiring authors to upload copies of their papers to [open] repositories. This has created a deep resource of legal open access papers…” And that’s what Unpaywall draws on.

This seems like quite a boon for researchers, journalists, students and policymakers. You can download the Unpaywall extension for Chrome and Firefox, or learn more about the new service at the Unpaywall website.

Note: Over at Metafilter, you can find a good list of sources of, or methods for, obtaining free academic content.

via London School of Economics/Metafilter

Follow Open Culture on Facebook and Twitter and share intelligent media with your friends. Or better yet, sign up for our daily email and get a daily dose of Open Culture in your inbox. 

If you’d like to support Open Culture and our mission, please consider making a donation to our site. It’s hard to rely 100% on ads, and your contributions will help us provide the best free cultural and educational materials.

Discover “Unpaywall,” a New (and Legal) Browser Extension That Lets You Read Millions of Science Articles Normally Locked Up Behind Paywalls is a post from: Open Culture. Follow us on Facebook, Twitter, and Google Plus, or get our Daily Email. And don’t miss our big collections of Free Online Courses, Free Online Movies, Free eBooksFree Audio Books, Free Foreign Language Lessons, and MOOCs.


The Fascinating Engraving Process Used to Turn Lincoln’s Penny Profile Into a Skull With Scrolls

Laughing Squid by Lori Dorn

Coin engraver Shaun Hughes demonstrated the fascinating process by which he transformed a 1973 Lincoln penny profile into a skull with decorative scroll flourishes. This craft, known as Hobo Nickel, is incredibly intricate, but Hughes walks the viewer through every step, making it seem easier than it is.

via The Awesomer

Related Laughing Squid Posts


Legendary Saxophonist Sonny Rollins Opens Up About Self-Confidence in a Lost 1985 Interview

In a beautiful episode of “Notes from the Ertegun Jazz Hall of Fame“, a collaborative series from Quoted Studios and Jazz at Lincoln Center, an animated version of legendary jazz saxophonist Sonny Rollins opened up about his sense of self-confidence, his endless drive to be the best version of himself and that seminal night in 1959 when he went to practice his horn on the Williamsburg Bridge during a self-imposed musical sabbatical. This interview took place with journalist Ben Sidran on November 14, 1985.

It was beautiful because you’re playing against the air. You know the sky it was just a beautiful place to practice a horn. It’s a magical thing you know the keys are there on the piano but what you do with them Tuesday night is going to be different than anything you could have thought about Sunday. So this is the magic of it and it’s a beautiful life.

https://player.vimeo.com/video/211519205

Related Laughing Squid Posts

VISIT WEBSITE