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",
},
];
One way, using reduce():
reduce(), for each object return a string (concatenating the previous value) that contains:
<h1> created with cat.Title<img> created with cat.ImageinnerHTML of your element<body> as democonst 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('');
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.