Search code examples
lit-elementlit-html

Cannot display child element


I'm a beginner lit-element developer and trying to solve a simple problem.

This is my html page:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>LitTest</title>
    <script src="webcomponents/webcomponents-loader.js"></script>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <svg id="canvas" style="width: 100%; height: 100%;">
      <es-postit></es-postit>
    </svg>
  </body>
</html>

And this is the component code:

import { LitElement, html, customElement, css } from "lit-element";

@customElement("es-postit")
export class PostIt extends LitElement {
  static styles = css`
    rect {
      fill: red;
    }
  `;

  render() {
    console.log("rendering element.");
    return html`<rect x="10" y="10" width="210" height="210" />`;
  }
}

As you can see there's nothing special. The problem is, I can't see the component on the page. But if I change the index.html to this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>LitTest</title>
    <script src="webcomponents/webcomponents-loader.js"></script>
    <style>
      html,
      body {
        width: 100%;
        height: 100%;
        padding: 0;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <svg id="canvas" style="width: 100%; height: 100%;">
      <rect x="10" y="10" width="210" height="210" />
    </svg>
  </body>
</html>

then I can see the rect on the page. Also if I get rid of all the svg related elements and turn them into divs, everything works just fine. Is it something to do with SVG?


Solution

  • After looking through the lit-html docs, I found the svg template function that does what I want. It renders the template in the svg namespace.