DEV Community

Cover image for Test Your Knowledge with Web Components
Kern Designs
Kern Designs

Posted on • Edited on

Test Your Knowledge with Web Components

The Project

I've said it once and I'll say it again. Web components are the future because of their versatility. I recently set out to recreate a flashcard using web components and though I should keep you all updated on the journey. Here is the original flashcard compared with my recreation below.
Original flashcard

Hannah's flashcard

As you can see they styling is the same, but the biggest difference is the ability to change with user input. In an attempt to allow the card to be used in HAX, I added that functionality. Below you can see me editing the flashcard.

The flashcard with editable properties

The same flashcard with different properties

The Process

So while this may seem like an easy implementation, it took a decent amount of tooling and wiring. In order to make the editable menu options I added the properties into the user menu with the json code shown below. This adds the textbox into the menu.

"settings": {
    "configure": [
      {
        "property": "front",
        "title": "Flash-Card-Question",
        "description": "The question that the user will be asked",
        "inputMethod": "textfield"
      },
      {
        "property": "back",
        "title": "Flash-Card-Answer",
        "description": "The answer to the question",
        "inputMethod": "textfield"
      }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Now that the ability is there I have to add the functionality so that is actually changes something. This requires wiring them together. In the JavaScript file you have to create the properties. You can see them below as the front(question) and back(answer) in the properties block. In the render function you can see the divs with slot called. Because of the way this is wired you have to add the slot to a div for HAX to find it.

  static get properties() {
    return {
      ...super.properties,
      inverted: { type: Boolean },
      keyword: { type: String },
      front: {type: String },
      back:{type: String },
      sideToShow: { type: String, reflect: true, attribute: 'side-to-show' },
    };
  }
Enter fullscreen mode Exit fullscreen mode
  render() {
    return html`
      <krusty-image img-src="${this.keyword}"></krusty-image>
      <flash-card-body sideToShow='${this.sideToShow}'>
      <slot slot="front" name="front"><div slot="front">${this.front}</div></slot>
      <slot slot="back" name="back"><div slot="back">${this.back}</div></slot>
      </flash-card-body>
    `;
  }
Enter fullscreen mode Exit fullscreen mode

As you can see this isn't terribly difficult but you do have to understand what is happening. If you want to see the whole project it is posted on github and on npmjs.

Top comments (0)