Replace access with lodash.get, make more declarative.

Lodash already has support for safe property access via the explicit
`get` method, and as a shorthand to many of the collection methods (such
as `sortBy`.

I also took this opportunity to refactor the code to be a bit more
functional, which allows us to place the list tiems inline with the rest
of the JSX, which I find far more readable.

Interesting project!
This commit is contained in:
Jordan Eldredge 2017-02-02 09:27:07 -08:00
parent 5f52e0b75e
commit df2c7ef323
2 changed files with 18 additions and 23 deletions

View file

@ -1,37 +1,22 @@
import React from 'react'
import { Link } from 'react-router'
import sortBy from 'lodash/sortBy'
import get from 'lodash/get'
import { prefixLink } from 'gatsby-helpers'
import { rhythm } from 'utils/typography'
import Helmet from "react-helmet"
import access from 'safe-access'
import { config } from 'config'
import include from 'underscore.string/include'
import Bio from 'components/Bio'
class BlogIndex extends React.Component {
render () {
const pageLinks = []
// Sort pages.
const sortedPages = sortBy(this.props.route.pages, (page) =>
access(page, 'data.date')
).reverse()
sortedPages.forEach((page) => {
// Posts are those with md extension that are not 404 pages OR have a date (meaning they're a react component post).
if (access(page, 'file.ext') === 'md' && !include(page.path, '/404') || access(page, 'data.date')) {
const title = access(page, 'data.title') || page.path
pageLinks.push(
<li
key={page.path}
style={{
marginBottom: rhythm(1/4),
}}
>
<Link style={{boxShadow: 'none'}} to={prefixLink(page.path)}>{title}</Link>
</li>
)
}
})
const sortedPages = sortBy(this.props.route.pages, 'data.date')
// Posts are those with md extension that are not 404 pages OR have a date (meaning they're a react component post).
const visiblePages = sortedPages.filter(page => (
get(page, 'file.ext') === 'md' && !include(page.path, '/404') || get(page, 'data.date')
))
return (
<div>
<Helmet
@ -43,7 +28,18 @@ class BlogIndex extends React.Component {
/>
<Bio />
<ul>
{pageLinks}
{visiblePages.map((page) => (
<li
key={page.path}
style={{
marginBottom: rhythm(1/4),
}}
>
<Link style={{boxShadow: 'none'}} to={prefixLink(page.path)}>
{get(page, 'data.title', page.path)}
</Link>
</li>
))}
</ul>
</div>
)