Skip to content
Advertisement

Dynamically create html pages

I’m trying to build a website, I have an API which extracts a list of products and gives me a JSON file which has all the info I need. What I wanted to achieve is to have a separate page created for each of the product – dynamically (since the JSON file will be changing). Is that possible with javascript/html?

Thank you

Advertisement

Answer

Of course. This is how all retail websites are created.

I suggest you start learning some javascript framework like ReactJS or Angular. In short, after the JSON is received from the server, it is passed to -what we call- a component as props (properties). The component holds some jsx or html that forms the “skeleton” of the user interface. The objects in the JSON (I assume each object is a product), fill the skeleton.

This is an example of a very very very basic structure for one single product. You can use a for loop or the map method to iterate over your JSON so you can display each product’s details in the following format:

In the following snippet, props could look like this {productImage:"imgur.com/blabal.png",productTitle:"Product X",price:3000}

function product(props){

return(
<div className="product-container">
<img className="product-image" src={props.productImage}
<span className="product-title">{props.productTitle}</span>
<span className="product-price">{props.price}$</span>
......
</div>
)
}

Each product will have its own object with its own productImage, productTitle and price among other things you choose to add.

So you’ll have 1,000 products (1,000 objects). You’ll pass the products one by one to the above snippet (as props), and it’ll display all of the products. Instead of writing 1,000 snippets for each product.

Obviously I can’t teach you ReactJS in one answer. I highly recommend you look into React. You can find many tutorials on Youtube. What you’re looking to do is very easy.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement