Embed Dev.to blog post with vanilla-JS
Vaishnav
Posted on December 5, 2020
Easiest guide to embed Dev.to blog post to your personal website using Javascript.
Recently, I started writing blog and also working on my portfolio. Portfolio is best way to showcase your Project, Technical blogs and more..
I'm working on portfolio site and hosting it using Github and Netlify. No Framework
It's static site, and I didn't want to manually update HTML every time I write blog, So here's solution I find out.
Codepen at the end
Let's Start π€
First thing I need is API to get data from Dev.to, I googled little bit and find the API.
https://dev.to/api/articles?username=
We don't need to give any other key:value just your username.
Here's the HTML
Working with JS
Initial Declaration
blogPos
is div where we want to show all our blog data.
You should assign your Dev.tousername
Creating helper functions
We are going to create few HTML elements using javascript. To create element we have method document.createElement()
.
createNode()
- creating element.
append()
- append element.
It's not necessary to create this function, I create them to make code simpler.
Create ul for list of elements.
const ul = createNode('ul');
ul.classList.add("blog-feed");
Important Part
I create buildURL()
function for API url with our username. It is assign to finalURL. This is our buildURL()
function buildURL(userName) {
return `${api}username=${userName}`;
}
Now fetch, fetches and we get response in object with series of methods. There are different methods, here we use JSON as we want to handle our data as JSON object.
Why I use posts.length = 5
?
Basic: Want to limit number of post we want to show.
Suppose you have 10-15 blog post, the fetch API will get every one of them. You can change how many post you want to show.
posts.forEach()
For every post we are going to create elements. Look,at that clean codeπ€© PS: Still room for improvement.
a.target = 'blank
- to open blog link in new tab.
p.classList.add()
- to add class to p tag.
a.href = post.url
- giving post url link to a:href tag.
a.innerText = 'post.title'
- post title to a tag inner text.
p.innerText = 'post.description'
post description to paragraph.
You can add more thing, like publish date, time, #tags, public reactions. So here I add public reactions.
small.innerText = 'π ' + post.public_reactions_count;
Now appending part,
li <- h2 <- a
li <- p
li <- small and
ul <- li
append(h2, a);
append(li, h2);
append(li, p);
append(li, small);
append(ul, li);
append(blogPos, ul)
- Adding this list to div element.
One thing Always create error handle. I didn't create error handler here.
Here's the pen
Hope this article helped you. If you have any suggestions or find any mistake please write to me.π
Posted on December 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.