Home > Enterprise >  How to populate a HTML div from array object?
How to populate a HTML div from array object?

Time:01-04

I was YouTube video on ReactJS where it populate a div container from a array object using .map() . Is there any way to do it using vanilla js or jquery in simple HTML ? ReactJS code is provided below -

ProductCategories.JSX

import { categories } from "../dataList";
import CategoryItem from "./CategoryItem";

<div className="* * *">
  {categories.map((item) => (
  <CategoryItem item={item} key={item.id} />
  ))}
</div>

CategoryItem.JSX

import styled from "styled-components";

<Container>
  <Image src={item.Image} />
  <Info>
    <Title>{item.Title}</Title>
    <Button>SHOP NOW</Button>
  </Info>
</Container>

dataList.js

export const categories = [
  {
    id: 1,
    Image: "https://i.ibb.co/CnkbTqm/download-ixid-Mnwx.jpg",
    Title: "Lorem",
  },
  {
    id: 2,
    Image: "https://i.ibb.co/CnkbTqm/download-ixid.jpg",
    Title: "Ipsum",
  },
  {
    id: 3,
    Image: "https://i.ibb.co/CnkbTqm/download.png",
    Title: "lorem",
  },
];

CodePudding user response:

One way, using reduce():

  1. Loop through the categories using reduce(), for each object return a string (concatenating the previous value) that contains:
    1. A <h1> created with cat.Title
    2. A <img> created with cat.Image
  2. Set the string as innerHTML of your element
    Using <body> as demo

const categories = [{id: 1, Image: "https://i.ibb.co/CnkbTqm/download-ixid-Mnwx.jpg", Title: "Lorem", }, {id: 2, Image: "https://i.ibb.co/CnkbTqm/download-ixid.jpg", Title: "Ipsum", }, {id: 3, Image: "https://i.ibb.co/CnkbTqm/download.png", Title: "lorem", }, ];

document.body.innerHTML = categories.reduce((prev, cat) => prev   `<h2>${cat.Title}</h2> <img src='${cat.Image}' />`, '');


We can get the same idea/behaviour/output using map() and join() instead off reduce() like so:

const categories = [{id: 1, Image: "https://i.ibb.co/CnkbTqm/download-ixid-Mnwx.jpg", Title: "Lorem", }, {id: 2, Image: "https://i.ibb.co/CnkbTqm/download-ixid.jpg", Title: "Ipsum", }, {id: 3, Image: "https://i.ibb.co/CnkbTqm/download.png", Title: "lorem", }, ];

document.body.innerHTML = categories.map(cat => `<h2>${cat.Title}</h2> <img src='${cat.Image}' />`).join('');

CodePudding user response:

you can use createElement() api https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement

here are some ideas in vanilla

var div = document.createElement('div');
var link = document.createElement('a');
var article = document.createElement('article');

and here in Jquery

var elem = $('<div></div>')

you can create element and append to the them container.

  •  Tags:  
  • Related