Another day, another blog!
In this blog, I will talk about how I displayed my blogs from my dev.to to my React portfolio website!
The inspiration for writing this blog is from Ms. Natalie De Weerd's blog in using the dev.to
API with PHP to make a blog feed. So, credits to Ms.Natalie for sharing her blog on utilizing dev.to
API!
But if you're here to see it in React, you can first read the docs using the API here.
API endpoint
Next, the endpoint that we're going to use is this;
https://dev.to/api/articles?username=tolentinoel
If you click that endpoint, you can see a JSON object with 12 of my articles in an array! Neat right? (You can just switch out the username at the end of the endpoint with your username)
Import React component
Now we have the endpoint working, we would need to fetch that data to be on our code and manipulate it to our liking. In my case, I wanted my blogs to be in a card component using react-bootstrap.
There are so many ways to display our data, but since I wanted it to be in cards, I imported the Card component from React-Bootstrap
import Card from 'react-bootstrap/Card'
Then we fetch the data and set it as our state.
componentDidMount(){
fetch('https://dev.to/api/articles?username=tolentinoel')
.then(res => res.json())
.then(data => {
this.setState({ blogs: data })
})
}
Once the state is set, we can now iterate through each article and create a card component in the DOM per blog.
I have tried having it displayed all of my blogs, but since I wanted more of a snippet of my most recent ones, I decided to use slice and only show the 4 recent ones (As you can see on the first line of code above).
And after a few CSS adjustments, here's a preview of my finished product!
Want to see it live? Here's my portfolio! Ellaine.dev
I hope this was easy to follow and gave you an insight into using dev.to
API to your React app!
Top comments (2)
I had no idea using an API to get your posts was even possible. That's definitely something I'll try to explore in the future! And... awesome post by the way :D
I didn't know of it as well before seeing the blog I referenced. I'm glad you find this interesting! :) Thank you!