DEV Community

artydev
artydev

Posted on • Updated on

You perhaps don't need any framework to use components in Javascript

Developping with components is at core of all modern frameworks.
In DML here is how to create a simple card component :

/* Definition of card component */
function Card(img) {
  let card = selectBase(div("", { class: csscard }));
  h1(img.title, { class: csstitle });
  image(img.src, { class: cssimgs, title: img });
  unselectBase();
  return card;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, it is just Javascript. DML is not a framework, it is a library which works directly in the browser like Jquery.

Here is a demo on how to use it :

import { selectBase, div, unselectBase, h1, image, _bgred } from "./dml";

import b from "bss";

b.css("body", {
  padding: 0,
  margin: 0,
  paddingTop: "50px"
});

let csscard = b`
  max-width: 400px;
  background:white;
  margin: 0 auto;
  margin-bottom: 10px;
  border: 1px solid black;
`;

let cssimgs = b`
  width: 100%;
  display: inline-block;
  position: relative;
  top: 4px;
`;

let csstitle = b`
  text-align: center;
  margin:0;
  padding: 0;
   font-size: min(7vw, 32px);
`;

let images = [
  {title: "American Eskimo", src: "https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg"},
  {title: "Rodhesian Ridgeback", src: "https://st2.depositphotos.com/1833015/5457/i/950/depositphotos_54570909-stock-photo-dog-breed-rhodesian-ridgeback.jpg"}
];

/* Definition of card component */
function Card(img) {
  let card = selectBase(div("", { class: csscard }));
  h1(img.title, { class: csstitle });
  image(img.src, { class: cssimgs, title: img });
  unselectBase();
  return card;
}

for (let img of images) {
  Card(img)
}

Enter fullscreen mode Exit fullscreen mode

You can play with it here : DemoCard

Another demo : UserCards

function  UserCard (user) {
  let card = selectBase(div("", { class: csscard }));
  let userdiv = selectBase(div("", {class: cssuser}));
  image(user.picture.thumbnail, {class: cssimg})
  div(user.name.first, {class: csstitle})
  unselectBase(2); //end card; end userdiv
  return card;
}

async function main (numUsers) {
  let req = await fetch(`https://randomuser.me/api/?results=${numUsers}`)
  let resp = await req.json();
  resp.results.map(UserCard)
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)