Ad

How Can I Create Monthly Archive List On Sidebar In Gatsby Blog?

- 1 answer

can somebody help me to create monthly archive list on Sidebar in my Gatsby blog ?

As I am relatively new in Gatsby, any suggestion/comments are highly appreciated !

What I would like to achieve is here
Year Month (number of posts)

I would like to list the 'year month' and 'number of posts' those which are posted in corresponding period, in Sidebar.

What I have done so far is creating 'PeriodList' component as below.

PeriodList component

import React from "react"
import kebabCase from 'lodash/kebabCase'
import './style.scss'
import { Link, StaticQuery, graphql } from "gatsby"

const PeriodList = () => (
  <StaticQuery
    query={graphql`
      query {
        allMarkdownRemark(limit: 2000) {
          group(field: frontmatter___date) {
            fieldValue
            totalCount
          }
        }
      }
    `}
    render={data => (
      <nav>
        <h1 className="periodlist-header">月別アーカイブ</h1>
        <ul className="period-list">
          {data.allMarkdownRemark.group.map(date => (
                <li className="period-list-item" key={date.fieldValue}>
                     <span className="period-list-icon"></span>
                     <Link className="period-list-item-link" to={`/${kebabCase(date.fieldValue)}/`}>
                         {date.fieldValue} ({date.totalCount})
                     </Link>
                </li>
            ))}
        </ul>
      </nav>
    )}
  />
)

export default PeriodList

As a result, I got the list below.
current list of archive in sidebar

It lists each post by date.

Can somebody support me how to show 'year month' and 'number of posts' for corresponding period in sidebar ?

Thank you so much for your support always and best regards.

Ad

Answer

All you need is to convert your data.allMarkdownRemark.group ARRAY before rendering ... it's just js

Your code is shortened - returns JSX directly render={data => ( JSX structure - but you can extend rendering 'flow' with any js you need that way:

// render takes a function
render={data => { 
  // js body here - any calculations/convertion needed 
  // to adapt your data to your rendering needs (`.map()`, `.reduce()`, etc.)
  const monthGrouppedData = someConvertDataFn(data.allMarkdownRemark.group);
  // return JSX
  return ( 
    {monthGrouppedData.map(month => ...`
Ad
source: stackoverflow.com
Ad