Adding your blogs on a portfolio with react and Hashnode API

Subscribe to my newsletter and never miss my upcoming articles

Hashnode is one of the best blogging platform ever built. Seriously it has all the features one would ever wish and that too with an eye-appealing user interface. The 👩‍💻 devblog is one of the best features of hashnode for reasons like

  • Markdown support
  • Syntax Highlighting & rich embeds
  • AMP Support
  • You own your own data
  • backup on Github
  • And you can host your blog on your own personal domain.

But what if you have a portfolio site and you want to add your blogs on the same domain without moving to another domain. Well, you can do that using Hashnode's GraphQL API. You can check out Hashnode's API playground and docs here.

hashnode api playground.png

Exploring the API docs

GraphQL is a query language for APIs. We send a GraphQL query to the API and get exactly what we need.

So If you go through the docs, you can find whatever you want and send that query to the API. Let's explore the docs and find the exact query for our blog posts.

hashnode docs.png

Once we find the posts we can decide what things we want to show on individual posts like title, brief, cover image, date of publishing, etc.

hashnode posts.gif

This is how our query will look now

const query = `
    {
      user(username: "rutikwankhade") {
        publication {
          posts{
            slug
            title
            brief
            coverImage
          }
        }
      }
    }
  `;

Fetching the blog posts

So I created a class component called Blogposts.js where I will call the API and display all the posts. Let's first call the fetchPosts function and console log the response to see if it works.


class Blogposts extends React.Component {
  state = {
    posts: []
  };

  componentDidMount() {
    this.fetchPosts();
  }

  fetchPosts = async () => {
    const response = await fetch('https://api.hashnode.com', {
      method: 'POST',
      headers: {
        'Content-type': 'application/json',
      },
      body: JSON.stringify({ query }),
    })
    const ApiResponse = await response.json();
    this.setState({ posts: ApiResponse.data.user.publication.posts});

    console.log(ApiResponse.data.user.publication.posts); 
  };

   render(){
        return(
            <h1>Hashnode api</h1>
        );
}

console.png

✨ Yay! We got the perfect response. It's an array of objects where each object has a title, slug, brief description, and cover image of a post.

Rendering the posts

First, we will map the array and then pass it's elements through props to the Post.js component. Here is how the render function of BlogPosts.js will look now.

render() {
        return (
            <div>
                {this.state.posts.map((post, index) => (
                    <a key={index} 
                         href={`https://blog.rutikwankhade.dev/${post.slug}`} >
                        <Post post={post} />
                    </a>
                ))}
            </div>
        );
    }

The slug will be useful here to link posts to the original blog posts. Now let's create a Post.js component for displaying each blogpost.

const Post = ({ post }) => {
    return (
        <div>
            <img src={post.coverImage} alt={post.title}/>
            <h2>{post.title}</h2>
            <p>{post.brief}</p>
        </div>
    )
}

After adding some styling to the components and a few more details, the final result looks awesome. You can see it live here. Also, you can find the complete code on this repository.

rutik-wankhadeblogs.gif

References


I keep writing about the things I learned and applied. So you can connect with me on Twitter, Github or Linkedin. Also, subscribe to my newsletter and stay up-to-date with my latest blog posts.

⚡ Happy learning!

Ahmed Altaai's photo

Rutik Wankhade Well done!

Yesterday I finished implementing it for my rework of my portfolio and started writing a blog about it.

I refreshed the main page of hashnode and saw that you've already posted a similar blog although with react.js, I'm doing it with Vue.js.

nonetheless great work and keep it up!

Rutik Wankhade's photo

Thanks. And I would love to read about how you implement it with Vue.js. 🙌 It's cool to see how we can implement same things with different technologies.

Ezenwankwo Ugochukwu's photo

Thanks for sharing. Will definitely need this!

Rahul's photo

I'm following and subscribing 3 people who give best articles, sources and tutorials, you're one of them from now. You're such an inspiration. Loved this article and all of them.

Rutik Wankhade's photo

Thanks, Rahul. That's so nice of you. You too have written some awesome content on your blog. And I really loved the new customized look of your blog. Looks stunning.🔥

Rahul's photo

Thank You. I used Edidiong's new article to get the source code and then customized the way I liked it.

Rutik Wankhade

Sujay Kundu's photo

Great Thanks for the tip ! I was planning this to do using Gatsby and Github Pages :D

Tapas Adhikary's photo

Rutik Wankhade, Thanks for sharing this. Bookmarked to revisit when I do it for my website.

Bhanu Teja Pachipulusu's photo

Very good article.

Didn't know that @hashnode has an official public GraphQL api. Will definitely be using it.

Andrew Baisden's photo

Pretty cool I just might have to give this a try.

Rutik Wankhade's photo

Yeah, Go on. It's fun.👍