About the Author:

Front-End Development Explained for Non-Developers (part 1)

January 29th, 2020

Front-end development is defined, by Wikipedia, as the “practice of producing HTML, CSS and JavaScript for a website or web application so that a user can see and interact with them directly.” Most people can make sense of basic HTML, CSS, and JavaScript (and that used to be enough). But in the last 5-10 years, front-end development has evolved and splintered into a miscellany of frameworks, libraries, build-tools, command line tools, and new languages.

This plethora of technologies makes it challenging for developers and next to impossible for lay people to follow this field. This post will attempt to explain the landscape of front-end development technologies (as of mid-2015) for a non-developer audience.

Part 1 will cover Libraries and Frameworks. Part 2 will cover build tools, command line tools, and new languages. Part 3 will provide 3 pieces of recommended reading.

Libraries

There’s an organization in Denver, Colorado called the Denver Tool Library. For a subscription fee, they let members borrow some of their 2000 different tools. People can come in to chisel wood, test circuits, or maybe take a tool out to use in their garden. The library offers specific tools with specific functionality that can be used as many times as members need.

Programming libraries work very much in the same way as a physical tool library. Libraries like jQuery, Handlebars, Underscore or Backbone give developers specific functions, methods, and objects they can use to achieve a particular task in their code. With one command or <script> tag, developers can bring a library in and have immediate access to its tools.

The library that has had the largest impact on web development in the last 10 years is jQuery. Among other things, jQuery simplifies creating JavaScript across browsers.

Handlebars is a “semantic web template system”. Template systems make it easy for developers to put dynamic content into a static page a user sees. {{ Curly Brackets }} (aka sideways mustaches) are put into the HTML for dynamic content. Handlebars swaps out values between the curly brackets with content from the program. An example of this in action:

This HTML table…

<tbody>

{{#users}}

<tr>

<td>{{fullName person}}</td>

<td>{{jobTitle}}</td>

<td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td>

</tr>

{{/users}}

</tbody>

…will become this table with the help of Handlebars. The brackets get filled in with dynamic content:

Underscore takes a different spin on the tool library metaphor. Underscore used to call itself ‘a utility-belt library’ for JavaScript. Underscore gives developers shorter, faster ways of doing common tasks like looping over an array or object (which are collections of data in JavaScript). Normal JavaScript provides a way of doing this but a library like Underscore (or Lodash) provides a shorter/simpler way of doing so.

Backbone is a library that makes it easier to better organize applications. Backbone is usually used with Underscore and jQuery, and sometimes with Handlebars to form a complete application framework. An application framework usually handles a lot of the common tasks in web development like handling HTTP requests, routing, organizing business logic, and views the clients will interact with. We’ll go over frameworks in the next section in more detail.

React is the hot library of 2015. React came out of Facebook’s struggle to get the Like Button count to work well. When people would push it, it was hard to get the like count right. React offers a new (and faster way) to create data-driven interactive user interfaces. It is actually used in production for hundreds of millions of users (Instagram/Facebook) so even though it’s new, it has been thoroughly ‘battle tested’.

Photo, Phone, Android, Instagram, User, Smartphone

React in action

The Frameworks

A framework is typically something that provides a structure or way of organizing something. A web application framework, like Ember or Angular, saves developers from having to set up common web development structures/tasks on their own.

Think of a framework like a prefab home. Prefab homes come with the most of the ground plan laid out. The electrical wiring, framing, drywall, and plumbing are generally installed and ready to go. The homeowner then customizes the home’s interior suit their tastes (colors, textures, floors, appliances). The homeowner still could tear down the walls and rework the structure but generally they will go with the defaults.

This metaphor has its limitations but think of a web framework as providing a starting structure and set of defaults within which the developer can make an application.

Angular has become, by far, the most popular JavaScript framework in use (as of 2015). Angular handles tasks like connecting to a database, allowing the user to interact with information on the page, and handling the URL routing (in the address bar). Angular makes it simple to create what are called Single Page Applications (SPAs). If you’ve used Google Maps or Gmail, you’re used to a using a page that updates without refreshing the entire page. It does this by using a technology called Ajax.

Ember is another JavaScript framework that gives developers a scaffolding and structure to develop applications. Ember has a number of ‘opinions’ (conventions) that are meant to increase developer productivity. In theory, this should make it easier for developers to join an Ember project than an Angular project. The tradeoff of this is that some feel restricted by it’s enforced structure.

Bootstrap and Foundation are front-end frameworks that focus on the look and feel of a site. Both can be utilized to easily develop good looking sites that work well across different screen sizes. Each gives you pre-defined CSS and HTML components. A Bootstrap component would be a something like this piece of HTML:

<ul class="nav nav-pills"> 
<li role="presentation" class="active"><a href="#">Home</a></li> 
<li role="presentation"><a href="#">Profile</a></li> 
<li role="presentation"><a href="#">Messages</a></li> 
</ul>

This allows a developer to quickly get a navigation menu that looks like this:

By using Bootstrap/Foundation, developers can avoid having to reinvent the wheel when they need something common like a navigation menu, progress bar, or drop-down menu.

Bootstrap is now used on nearly 10% of internet sites. You can see a variety of sites that use Bootstrap at their showcase site.

Google Trends Proxy on Framework Popularity

Summary

This post gave a high level explanation on libraries and frameworks. Hopefully, you have a better sense of how each work now. Part 2 of this blog series will explore and explain how build tools, command line tools, and new languages work in front-end development.

About the Author:

15 Blogs Every Javascript Developer Should Follow in 2020

January 7th, 2020

I’ve been following the most interesting JavaScript blogs quite for a while now (this is a part of my job running https://weekendjs.com/). There are many of them. More than you might think. There are blogs started more than ten years ago, and there are relatively new ones. Some bloggers are JavaScript superstars, and others are regular engineers like you and me. Some blogs are focused on a particular ecosystem (say Angular or React, or Vue), while others are rather general.

The exciting thing is that the number of good blogs with really robust material keeps growing from one year to another. It is a promising trend, which hopefully will continue.

A few words about who makes it into the list: only the bloggers who write relatively often (at least once per month). Those are all personal blogs, not hubs, companies, etc. And of course, the main metric is the quality of the material.

OK, enough words. Please welcome, in no particular order, the top 15 blogs a JavaScript developer should follow in 2018.

2ality

The author of the “Exploring ES6” book, Dr. Axel Rauschmayer is long known for his deep and comprehensive articles. They are always well-structured and tend to cover the topics in every detail. Usually he writes about ES6/7/8 features and how to use it, but recently, for example, he did a series of articles on ReasonML, which is a hot new JS-transpilable language from Facebook.

David Walsh

David Walsh is an engineer who works at Mozilla from Madison, Wisconsin. David writes regularly (several times per month). His posts are about web development in general. Usually, these are small, understandable pieces for a broad audience on JavaScript’s new features, Node, and more.

Reginald Braithwaite

Reginald “raganwald” Braithwaite, is the author of brilliant “JavaScript Allongé,” one of my favorite JavaScript books. If you haven’t read it, go ahead and do it. Seriously, it’s a pure pleasure, I promise. As you might expect, he writes a lot on functional-related topics. His articles are probably not for beginners and instead aimed at a more experienced audience.

Michael Herman

Michael Herman is a developer and public speaker. He writes about a lot of stuff such as Python, Docker, etc. Technically, I could leave him out of this list. But his write-ups on JavaScript and related material are extremely practical and helpful, so I just can’t leave out his brilliant blog.

Addy Osmani

I’m not sure I need to introduce Addy Osmani. He is a Chrome core developer, a web performance evangelist, and a public speaker. You probably use libraries he has written on a daily basis; just check his GitHub. He also wrote the very popular “Learning JavaScript Design Patterns” book. In his blog though, he writes a lot on Progressive Apps and is one of the core contributors to the concept.

Ponyfoo

This one is easily recognizable by the iconic pixelated image of a unicorn. The author writes lots about new ECMAScript features, in particular modules, and is (as you might expect) in the middle of writing a book about modules.

Dave Ceddia

Dave’s first post dates back to 2015. And it was about Angular 2 (yeah, can you believe it? Time runs so fast). In 2017, though, it seems as if he changed his preferred framework and started writing more on React. He’s also an author of a lovely little book called “Pure React” which is aimed at starters.

Todd Motto

Speaking of Angular, it’s surprisingly difficult to find robust material on the topic. It’s understandable, perhaps, since React seems to be a lot more fun to write about. Well, at least we have this guy. Todd writes a lot on connected topics (TypeScript, NGRX), speaks at the conferences and also does courses. He’s easily the best individual Angular blogger out there.

Tyler McGinnis

Tyler McGinnis is the author of many thorough React courses. So, as you might expect, he also writes a lot about React both Web and Native. His blog also contains a lot of video materials, which are a joy to watch.

John Papa

John Papa is a developer advocate, public speaker, and of course, a blogger. He also authored several courses on for Pluralsight. He used to write a lot on Angular, especially Angular 1, but it seems he’s more into Vue now. If you’re interested in this React alternative you should follow this guy.

Valentino G.

This guy writes a lot of different topics, including Django and Node. Most often he writes about React and friends.

Ben Nadel

I didn’t know about this one until recently, but now it’s easily one of my favorite JavaScript blogs. My favorite part is that he writes a lot about UX and its intersections with JavaScript. Highly recommend it!

Bram Van Damme

It’s interesting that lots of bloggers are from Europe. Like Bram, who is an engineer from Belgium. He writes about JavaScript and also more in general about the web and web development.

Ivan Akulov

Ivan writes about React and Webpack, and also in general about different optimizations you’ll need to do as a web developer. His write-ups are highly practical, and may not suit the beginners.

Robin Wieruch

Robin works in Berlin. He writes a lot (and quite often) about React and friends. But also (and that’s what makes him interesting) he writes about stuff like AI and machine learning. There aren’t a lot of places where you can read articles like “A Web Developer’s Guide to Machine Learning in Javascript” or “Neural Networks in Javascript.” If you’re interested in those topics, you definitely need to follow Robin.

I hope you liked this list. Now go ahead and add them to your preferred RSS reader as I did and enjoy the perpetual flow of the best articles from the JavaScript world!

About the Author:

Adding Authentication in AWS with Amplify

October 4th, 2019

If you’re familiar with using AWS for user authentication, DynamoDB, AppSync and other services in your app or website, you’ll love Amplify.

Amplify is a command-line interface that takes a few shortcuts, avoids the clicking and navigation and also makes a few wise decisions for you. Granted, you can customize things as you wish. And you can always go straight to the console source and make changes. But most of the time, using Amplify will do what you want faster and easier.

The first thing you need to do is install Amplify. You’ll need an AWS account and then run a few commands. You can see the details here: https://aws-amplify.github.io/docs/

Initialize a Project

Once it’s installed, you’re ready to go. I’ll use an iOS app but you can use basically the same steps for Android or a web app.

Navigate in the terminal to your project. From there, you’ll create your app’s existence with AWS with this command:

amplify init

The first thing it asks is for you to pick an editor:

I usually use Vim because it launches in the same terminal window.

Then it asks you to verify the type of project you’re working on. It can usually detect correctly based on the files:

Then you need to pick a profile (or create one on AWS which it helps you with):

Then it does it’s magic… and prints out a lot of lines. You can watch as it creates everything it needs. It will create a bucket in S3 for the deployment files, IAM roles as needed for running and accessing various pieces and a CloudFormation to manage it all.

The best part is you really don’t have to care! 🙂 Of course it’s always good to know what’s going on. I highly recommend going to each of the places listed in the AWS console to see what’s created.

Once the project is all setup, you’re ready to add features from AWS.

Help

If you run just “amplify” you get some basic help:

The key things you’ll tend to do are these:

amplify add <category> – This is how you add various services. If you add api, you’re adding AppSync (and possibly more like DynamoDB). If you add auth, that’s authorization using Cognito. Storage is S3 and so on.

Amplify does a great job of walking you through each one that while knowledge of each is great, it might not be necessary. Again, however, I highly recommend you understand what’s going on in the background.

I’d suggest using Amplify as a powerful tool to do what you already know about. I do not recommend using Amplify as a way to avoid learning the functionality of AWS.

Add Authorization

So let’s add a feature via Amplify to our app. We’ll use the command:

amplify add auth

One funny thing about amplify is that you can add a category with “amplify add <category>” or “amplify <category> add.” It’s like you can tell amplify “add this category” or you can tell a category to be added. Try not to let it bug you.

The first question you’ll be added is if you want to use the default configuration:

I like the default configuration. If you want to know more, select “I want to learn more” which displays this:

Again, I recommend learning about Cognito to understand the details. For this tutorial, we’ll go with the default.

It will set up the configuration for authorization to use a username, email and password for new accounts.

Amplify does this locally (and explains so at the end of the execution). So the configuration and everything is setup in files under the directory of your project.

It also mentions how you can push the change to AWS with the push command. To get it to AWS, you run:

amplify push

It will have you verify the changes before continuing:

In some cases there are more questions to answer and typically the default answer (e.g., Y/n – the capital letter being the default) is a good answer and you can just hit Enter on the keyboard.

Pushing to AWS can take a few minutes. Many lines will print out that look similar to when you created the project. Hopefully it ends with “All resources are updated in the cloud” and a satisfying green checkmark. 🙂

Cognito

Once it’s pushed to the server you can view the details at: https://console.aws.amazon.com/cognito/users

Of course you won’t have any users yet:

And locally you’ll have a new file that’s very important. It’s named awsconfiguration.json and it’s in the same directory your project is in:

This configuration file holds the details of the setup you created on AWS. It’s the file that you’ll include in your project (in this case Xcode) for access to the services and features.

As the extension implies, it’s a JSON file:

It lists the authentication related details the CocoaPods (iOS) will use to access AWS. As other categories are added via amplify, more items will be added to the awsconfiguration.json file.

If you include the file in your project where it is, you won’t need to update the file in your project as you add more services.

App Code

To add authentication to your code, you can visit the AWS documents per platform:

https://aws-amplify.github.io/docs/ios/authentication#initialization

https://aws-amplify.github.io/docs/android/authentication#initialization

https://aws-amplify.github.io/docs/js/authentication#configure-your-app

On the left side you’ll see a listing of other categories you can add similarly to your project.

For iOS, once you install the CocoaPods, checking to see if the user is logged in is pretty easy along with some other useful properties:

And showing the login/create account UI is similar:

Conclusion

Hopefully this removes some of the mystery of Amplify. I recommend trying it out and seeing how well it works for you. I’ve gotten pretty comfortable with it to the point that I don’t load up much of AWS to verify what it’s doing anymore.

Another great command in amplify is one that cleans everything up (for the given project). That way you can play around with it and remove it all easily. 🙂

amplify delete

 

About the Author:

Gatsby Tutorial Post Part 2: NetlifyCMS and Styling

April 29th, 2019

This is the 2nd part of a tutorial series on building fast and elegant sites with Gatsby, Material-ui, and NetlifyCMS (part 1 here). The previous part of the tutorial showed how to setup Gatsby and create pages manually as well as dynamically using gatsby-node.js. This part of the series will show the following:

  • Creating the Courses Page and Individual Courses
  • Adding Images to the Courses/Posts
  • Install Material-UI plugins and style all pages with Material-UI
  • Installing NetlifyCMS to allow non-technical users to make content changes
  • Adding More Fields Types to the Courses (that work out of the box with NetlifyCMS)

Demo Site (Here’s where we’re going to get to)

Github Repo (If you’d like to jump right into the code)

Creating the Courses Page and Individual Courses

Our demo site features both blogs (which we did previously) and courses (which we’ll do now). Similar to the blogs, this involves creating a parent /courses page, a course template, a courseitem component (for the list on /courses, and the markdown files for the courses. So let’s first create the main /courses page (that will list all of the courses) and pages for each course.

Here’s how I created each of the pages:

/pages/courses.js

import React from "react"
import { Link, StaticQuery, graphql } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"
import CourseItem from "../components/CourseItem"

class CoursePage extends React.Component {
 render() {
   const { data } = this.props

   const { edges: posts } = data.allMarkdownRemark

   return (
     <div>
       <Layout>
         <SEO title="Courses Page" />
         <h1>Courses Page</h1>

         <div
           style={{
             display: "flex",
             justifyContent: "space-evenly",
             flexWrap: "wrap",
           }}
         >
           {posts &&
             posts.map(({ node: post }) => (
               <CourseItem
                 key={post.id}
                 post={post.frontmatter}
                 style={{ marginRight: 10, width: "50%" }}
                 slug={post.fields.slug}
                 excerpt={post.excerpt}
               />
             ))}
         </div>
       </Layout>
     </div>
   )
 }
}

export default () => (
 <StaticQuery
   query={graphql`
     query CoursePageQuery {
       allMarkdownRemark(
         sort: { order: DESC, fields: [frontmatter___date] }
         filter: { frontmatter: { templateKey: { eq: "single-course" } } }
       ) {
         edges {
           node {
             excerpt(pruneLength: 100)
             id
             fields {
               slug
             }
             frontmatter {
               title
               templateKey
               date(formatString: "MMMM DD, YYYY")
             }
           }
         }
       }
     }
   `}
   render={data => <CoursePage data={data} />}
 />
)

/templates/single-course.js

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import { Link } from "gatsby"

const CoursePage = ({ data }) => {
 const { markdownRemark: post } = data

 return (
   <Layout>
     <Link to="/courses">
       <p>← Back to Courses</p>
     </Link>

     <h1>{post.frontmatter.title}</h1>
     <h4>{post.frontmatter.date}</h4>
     <p dangerouslySetInnerHTML={{ __html: post.html }} />
   </Layout>
 )
}

export default CoursePage

export const CoursePageQuery = graphql`
 query CoursePage($id: String!) {
   markdownRemark(id: { eq: $id }) {
     html
     frontmatter {
       title
     }
   }
 }
`

/components/courseitem.js

import React from "react"
import { Link } from "gatsby"

function CourseItem(props) {
 const { post, slug, excerpt } = props

 return (
   <div>
     <Link to={slug}>
       <h1>{post.title}</h1>
     </Link>
     <h3>{excerpt}</h3>
   </div>
 )
}

export default CourseItem

/courses/intermediate-react.md

---

templateKey: single-course

title: intermediate React

date: 2019-04-15T16:43:29.834Z

description: An intermediate React course

difficulty: Intermediate

---

what a course, what a course…….

/courses/cool-course.md etc

---

templateKey: single-course

title: Great course on JS

date: 2019-04-15T16:43:29.834Z

description: A great course

difficulty: Beginner

---

what a course, what a course...what a course, what a coursewhat a course, what a course...what a course, what a course

what a course, what a course...what a course, what a course

what a course, what a course...what a course, what a course

what a course, what a course...what a course, what a course

What’s going on here? Let’s review:

Gatsby-node.js creates the course pages using the appropriate template with this section of the code:

...

component: path.resolve(

`src/templates/${String(edge.node.frontmatter.templateKey)}.js`

),

…

In this case, it would be using single-course.js.

Within single-course.js there is a page query at the bottom. This queries for the right markdown file (using the id found in context) so that those specific pages will have the right title and html (from markdown) to display.

Within the courses.js file, we’re using a Static Query to query/search for the courses that have the templateKey of single-course and making a list of the courses (using the simple CourseItem.js component for help). This gives us a very basic (but functional) /courses page like this:

And an individual course page like this:

So these are pretty bland pages, unless you’re a hardcore minimalist. I’ll show you some Gatsby image plugins now that will add some color/life to these posts/courses.

Adding Images to the Courses/Posts

One of the top selling points of Gatsby is speed. Poorly sized or slow loading images are one of the easiest ways to make a website feel sluggish so this is an obvious area to optimize first. Two Gatsby plugins (gatsby-image and gatsby-transformer-sharp) are amazing tools for working with and optimizing Gatsby images. The latter leverages the Sharp image library, which is a very popular node module for resizing images. I’ll show you now to how add images to the course and post pages.

First, we need to install the plugins:

npm install --save gatsby-image gatsby-transformer-sharp gatsby-plugin-sharp

We’re also going to add a plugin that will allow us to access relative image paths in the project:

npm install gatsby-remark-relative-images --save

This will make for working with NetlifyCMS images easier later.

Then add them to the gatsby-config.js, within the big array of plugins like so:

 'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-relative-images',
          },
          {
            resolve: 'gatsby-remark-images',
            options: {
              // It's important to specify the maxWidth (in pixels) of
              // the content container as this plugin uses this as the
              // base for generating different widths of each image.
            
              maxWidth: 590,
            },
          },
          {
            resolve: 'gatsby-remark-copy-linked-files',
            options: {
              destinationDir: 'static',
            },
          },
        ],
      },
    },
{
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/static/img`,
        name: 'uploads',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/pages`,
        name: 'pages',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/src/images`,
        name: 'images',
      },
    },

Now we can add the images to our posts. Create a folder called /static and a folder within that call img. That’s where the images will live. I downloaded some demo images for this fake courses and put them in the folder.

Now within the individual course markdown files, we need to add the images within the frontmatter (—) headings like so:

---

[more items]

image: /img/[imagename].jpeg

---

Now, we’ll edit the single-course.js page to be able to query for this image and render it on the page. Change the GraphQL query at the bottom of the page to include the image query, like so:

export const CoursePageQuery = graphql`
  query CoursePage($id: String!) {
    markdownRemark(id: { eq: $id }) {
      html
      frontmatter {
        title
        image {
          childImageSharp {
            fluid(maxWidth: 500, quality: 100) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

This is using the gatsby-plugin-sharp plugin to render a fluid image with a maxWidth of 500 pixels. Right here within the GraphQL query, we’re able to choose how we’d like to receive the image in our component/html. This plugin has extensive documentation that can be found here.

Now, within the the single-course.js, we’ll use Gatsby-image to render the image in the html. It’s a simple import:

import Img from "gatsby-image"

And then a simple enough component to render.

<Img fixed={post.frontmatter.image.childImageSharp.fluid} />

This is how you add the right plugins, the files, and the queries to be able to use plugins within Gatsby.

Installing NetlifyCMS

NetlifyCMS (like an CMS) allows for non-technical users to edit content on a site. This allows people in marketing or content roles the freedom to create and frees up developers from having to do these sorts of small tasks. As was mentioned before, NetlifyCMS is made by static hosting service Netlify, but they can each be used separately from each other. Gatsby can be easily configured to work with WordPress, Contently, and many other data sources. NetlifyCMS has great docs, a generous free tier, and easy-to-use authentication.

NetlifyCMS is easy to configure with Gatsby using, you probably guessed it, gatsby-plugin-netlify-cms. Install it using npm and add it to gatsby-config.js:

npm install gatsby-plugin-netlify-cms --save

// gatsby-node.js

},.......[other plugins]

`gatsby-plugin-netlify-cms`,

….[other plugins] {

NetlifyCMS needs a config.yml file, which tells it which fields can be changed within the CMS. Create a folder called ‘admin’ within the Static folder and put the following config.yml file in it:

backend:
  name: git-gateway
  branch: master

media_folder: static/img
public_folder: /images

collections:
  - name: "pages"
    label: "Pages"
    files:    
      - file: "src/pages/about.md"
        label: "About"
        name: "about"
        fields:
          - {
              label: "Template Key",
              name: "templateKey",
              widget: "hidden",
              default: "about-page",
            }
          - { label: "Title", name: "title", widget: "string" }
          - { label: "Body", name: "body", widget: "markdown" }
  - name: "blog"
    label: "Blog"
    folder: "src/pages/blogs"
    create: true
    slug: "{{year}}-{{month}}-{{day}}-{{slug}}"
    fields:
      - {
          label: "Template Key",
          name: "templateKey",
          widget: "hidden",
          default: "single-blog",
        }
      - { label: "Title", name: "title", widget: "string" }
      - { label: "Publish Date", name: "date", widget: "datetime" }
      - { label: "Description", name: "description", widget: "text" }
      - { label: "Body", name: "body", widget: "markdown" }

  - name: "courses"
    label: "Courses"
    folder: "src/pages/courses"
    create: true
    slug: "{{year}}-{{month}}-{{day}}-{{slug}}"
    fields:
      - {
          label: "Template Key",
          name: "templateKey",
          widget: "hidden",
          default: "single-course",
        }
      - { label: "Title", name: "title", widget: "string" }
      - { label: "Publish Date", name: "date", widget: "datetime" }
      - { label: "Description", name: "description", widget: "text" }
      - { label: "Body", name: "body", widget: "markdown" }
      - { label: Image, name: image, widget: image }

This creates 3 collections within the CMS: one for updating the about page, one for the courses, and one for the blogs. The ‘widgets’ are NetlifyCMS widgets and should be self-explanatory in a moment. With the above config.yml, this is what my admin interface looks like:

Within the Courses Collection, I see this:

Take a look, again, at the config.yml.

Notice how the fields with this file line up with what you’re seeing in the CMS image above? The template key is hidden so it doesn’t show. But right there are string widget (aka text field) for Title, Description, and Body. And there’s a datetime widget (a datepicker) for Publish Data. NetlifyCMS is really just an interface for making changes to our markdown files here. The config.yml serves as a way to tell Netlify which fields are available for editing. NetlifyCMS features a wide variety of default widgets and you can even make custom ones.

Source: https://www.netlifycms.org/docs/widgets/

Although this takes some setup work, this workflow is extremely powerful for using Github markdown files as a CMS.

The final thing needed here is making the images hosted in static/img available for NetlifyCMS to use.

Add this to the top of the file within Gatsby-node.js

const { fmImagesToRelative } = require('gatsby-remark-relative-images')

And add this method call within the onCreateNode block:

exports.onCreateNode = ({ node, actions, getNode }) => {

const { createNodeField } = actions

fmImagesToRelative(node)

This plugin was specifically built to make NetlifyCMS play nice with relative image paths. Failure to add this config right will send you to bug hell (e.g. “Field “image” must not have a selection since type “String” has no subfields.”)

.

Styling it all with Material-UI

We’ve built out our posts, blogs, and about page. Now we’ll see how to style out all of the pages using the most popular React UI framework, Material-ui. Material-ui has nearly 50,000 stars on Github and over 1,000 contributors. It is a React implementation of Google’s Material Design principles. Material-ui gives React developers a wide variety of components, styling, and utilities for making their sites aesthetically pleasing and easy to use. If you don’t want your site to look like a generic Googly app, Material-ui is supremely easy to customize to your liking.

There are many ways to add Material-ui to a Gatsby project. Material-ui has a Gatsby starter to use. Another developer made a dedicated Gatsby-starter with Material-ui. But I find the easiest way to add Material-ui to Gatsby is with gatsby-plugin-material-ui. The previous two work but they are much more complicated. Plugins are one of the awesome parts of Gatsby: Just install the plugin, add it to gatsby-config.js and you’re good to go. Here’s how to do just that:

npm install gatsby-plugin-material-ui @material-ui/styles

Edit gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-material-ui`,
      options: {
      },
    },
  ],
};

If you’ve worked with Material-ui before, you’ve probably played around with its theming capabilities. Material-ui themes allow you to establish a global theme that can be called from various child components. This makes it easier to create one coherent look and feel (vs. having pages/components with different styles, which can look sloppy). With the gatsby-plugin-material-ui plugin, this theme will go in that options object in the config above like so:

options: {        
        theme: {
          palette: {
              primary: {
                  main: '#BA3D3B', // new color here 
              } 
          },
      },

Now we can import material-ui components anywhere within the our Gatsby project. Here’s how I changed the single-course.js page:

imports...
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
...
import Avatar from '@material-ui/core/Avatar';

const styles = theme => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    padding: theme.spacing.unit * 2,
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
  title:{
    marginBottom:'.2em'
  },
  backButton: {
    textDecoration:'none'
  },
  bigAvatar: {
    '& img':{
      margin: 10,
      width: 60,
      height: 60,
    },
    width:100,
    height:100,
    border:'1px solid grey'
  
  },
});

const CoursePage = ({ data, classes }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
       <Link to='/courses' className={classes.backButton}>
      <p>← Back to Courses</p>

      </Link>
      
      <Grid container spacing={24}>
       
        <Grid item xs={9}>
          <h1 className={classes.title}>{post.frontmatter.title}</h1>
          <h4>{post.frontmatter.date}</h4>
          <p dangerouslySetInnerHTML={{ __html: post.html }}/>  
        </Grid>    
        <Grid item xs={3}>
        <Avatar src={post.frontmatter.image.childImageSharp.fluid.src} className={classes.bigAvatar} />
       
        </Grid>   
      </Grid>
  
    </Layout>
  )
}
export default withStyles(styles)(CoursePage);

[page query removed for brevity]

Here’s how I changed the single-blog template:

...
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
...
import Layout from '../components/layout'
import Img from "gatsby-image"
import { Link } from "gatsby"

const styles = theme => ({
  root: {
    flexGrow: 1,
  },
  paper: {
    padding: theme.spacing.unit * 2,
    textAlign: 'center',
    color: theme.palette.text.secondary,
  },
  title:{
    marginBottom:'.2em'
  },
  backButton: {
    textDecoration:'none'
  }
});

const BlogPage = ({ data, classes }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
      <div className={classes.root}>
      <Link to='/blog' className={classes.backButton}>
      <p>← Back to Blog</p>

      </Link>
      
      <Grid container spacing={24}>
        <Grid item xs={3}>
          <Img fluid={post.frontmatter.image.childImageSharp.fluid} />
        </Grid>
        <Grid item xs={9}>
          <h1 className={classes.title}>{post.frontmatter.title}</h1>
          <h4>{post.frontmatter.date}</h4>
          <p dangerouslySetInnerHTML={{ __html: post.html }}/>  
        </Grid>       
      </Grid>
      </div>
    
    </Layout>
  )
}


export default withStyles(styles)(BlogPage);

[page query removed for brevity]
`

Here’s the about page:

...
import { withStyles } from '@material-ui/core/styles';

const styles = theme => ({
  heroText: {
    color:'white',
    textAlign: 'center',
    lineHeight:7,
    marginTop:-20
  },
  mainBlogCopy: {
    marginTop: theme.spacing.unit,
  },
  blogText:{
    color:theme.palette.primary.main
  }
});

const AboutPage = ({ data, classes }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
      <div style={{
        backgroundImage: `url(${post.frontmatter.image.childImageSharp.fluid.src})`,
        height:300
      }}>
      <h1 className={classes.heroText}>{post.frontmatter.title}</h1>
      </div>
      <div className={classes.mainBlogCopy}>
       <p className={classes.blogText} dangerouslySetInnerHTML={{ __html: post.html }}/> 
      </div>
      
    </Layout>
  )
}

AboutPage.propTypes = {
  data: PropTypes.object.isRequired,
}

export default withStyles(styles)(AboutPage);

[page query removed for brevity]

Here’s what I added to the home page to make it look a little more like appendTo:

….
import { Link, StaticQuery, graphql } from "gatsby"
import Grid from "@material-ui/core/Grid"
import BlogItem from "../components/BlogItem"
import { withStyles, withTheme } from "@material-ui/core/styles"
import Button from "@material-ui/core/Button"
import Typography from '@material-ui/core/Typography'
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';


const styles = theme => ({
  mainBlogArea: {
    paddingTop: '20px !important',

  },
  redBox:{
    padding:30,
    paddingTop:50,
    height:200,
    backgroundColor:'#AC4839',
    marginBottom:30
  },
  greyBox:{
    padding:30,
    paddingTop:50,
    height:200,
    backgroundColor:'#D9D8D8'
  },
  blackButton:{
    backgroundColor:'black',
    color:'white'

  },
  redButton:{
    backgroundColor:'#AC4839',
    color:'white'

  },
  TabsSection:{
    marginTop:30,
    backgroundColor:'white',
    border:'1px solid grey',
    height:300,
  },
  Tab:{
      width:10
  }

  
})

const IndexPage = props => {
  const { data, classes } = props
  // const { edges: posts } = data.allMarkdownRemark

  return (
    <Layout>
      <SEO title="appendTo Home" keywords={[`Courses`, `Training`, `react`]} />

      <Grid container spacing={24}  className={classes.mainBlogArea}>
        <Grid item xs={8}>
          <div >
            {data.map(item => (
              <BlogItem
                key={item.id}
                post={item.frontmatter}
                image={item.frontmatter.image.childImageSharp.fluid.src}
                slug={item.fields.slug}
                date={item.frontmatter.date}
              />
            ))}
          </div>
        </Grid>
        <Grid item xs={4}>
          <div className={classes.redBox}>
            <Typography variant="h5" style={{color:'white'}}>
              Custom Private Courses
            </Typography>
            <Button variant="contained" className={classes.blackButton}>
              Get Started
            </Button>
          </div>

          <div className={classes.greyBox}>
          <Typography variant="h5">
              Live Public Courses
            </Typography>
            <Button variant="contained" className={classes.redButton}>
              Sign Up Today
            </Button>
          </div>

          <div className={classes.TabsSection} >
          <AppBar position="static">
            <Tabs>
              <Tab label="Popular" className={classes.Tab} />
              <Tab label="Recent" className={classes.Tab} />
        
            </Tabs>
            </AppBar>


          </div>
        </Grid>
      </Grid>
    </Layout>
  )
}

const StyledUpIndexPage = withStyles(styles)(IndexPage)

export default () => (
  <StaticQuery
    query={graphql`
      query IndexPageQuery {
        allMarkdownRemark(
          sort: { order: DESC, fields: [frontmatter___date] }
          filter: { frontmatter: { templateKey: { eq: "single-blog" } } }
        ) {
          edges {
            node {
              excerpt(pruneLength: 40)
              id
              fields {
                slug
              }
              frontmatter {
                title
                templateKey
                date(formatString: "MMMM DD, YYYY")
                image {
                  childImageSharp {
                    fluid(maxWidth: 1400, quality: 100) {
                      ...GatsbyImageSharpFluid
                    }
                  }
                }
              }
            }
          }
        }
      }
    `}
    render={data => (
      <StyledUpIndexPage
        data={data.allMarkdownRemark.edges.map(item => item.node)}
      />
    )}
  />
)

And finally, here’s what I added to the NavBar to allow for navigating between the pages:

import { Link } from "gatsby"
import React from "react"
import { withStyles } from "@material-ui/core/styles"
import AppBar from "@material-ui/core/AppBar"
import Toolbar from "@material-ui/core/Toolbar"
import Button from "@material-ui/core/Button"

import { StaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"


const styles = {
  root: {
    flexGrow: "1 !important",
  },
  appbar: {
    backgroundColor: "#AC493A",
  },
  grow:{
    flexGrow:1
  },
  link: {
    color: `white`,
    textDecoration: `none`,
  },
}

class Header extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    const { classes } = this.props

    return (
      <div className={classes.root}>
        <AppBar position="static" className={classes.appbar}>
          <Toolbar>
            <div className={classes.grow}>
              <Link to='/' >
              <StaticQuery
                query={graphql`
                  query {
                    file(relativePath: { eq: "appendto_logo.png" }) {
                      childImageSharp {
                        # Specify the image processing specifications right in the query.
                        # Makes it trivial to update as your page's design changes.
                        fixed(width: 150) {
                          ...GatsbyImageSharpFixed_noBase64
                        }
                      }
                    }
                  }
                `}
                render={data => <Img  critical={true} fadeIn fixed={data.file.childImageSharp.fixed} />}
              />
              </Link>
            </div>
            <div>
              <Link to="/about" className={classes.link}>
                <Button color="inherit">About</Button>
              </Link>

              <Link to="/blog" className={classes.link}>
                <Button color="inherit">Blog</Button>
              </Link>

              <Link to="/courses" className={classes.link}>
                <Button color="inherit">Courses</Button>
              </Link>
            </div>
          </Toolbar>
        </AppBar>
      </div>
    )
  }
}

export default withStyles(styles)(Header)

And here’s what we end up with: https://appendtostaticstyled.netlify.com/

We have here a site that we can continue to build upon and style with Material-ui. All users can make tweaks or changes using NetlifyCMS. And finally, this site is blazing fast and consists of static files that can be served for cloud storage service or CDN.

This starter project is a great way to start any project and I hope these two long posts helped you understand how it came together.

Recommended Reading

This tutorial showed you the essentials of Gatsby. That said, even with nearly 5500 words, it had to skip over a number of topics. Here’s some posts I recommend reading to get a better understanding of Gatsby:

About the Author:

Build Fast and Elegant Sites with Gatsby, NetlifyCMS and Material-UI

April 27th, 2019

This tutorial will show you how to use Gatsby, NetlifyCMS, Netlify, and Material-UI to build out a multi-page site that can be updated with an intuitive CMS. Before diving into the code, I’ll first tell you about the the tools we’ll be working with. Part 2 is here (if you need to skip ahead).

Gatsby

Gatsby is React-based framework that has recently gained a lot traction and use in production. AirBnb, Flamingo, and Impossible Foods are all companies using Gatsby to build production sites and apps. Gatsby sites get built with React, GraphQL, Gatsby plugins, and some sort of CMS. Gatsby outputs production assets as HTML/CSS/JS files that can be served from a cloud host like AWS S3 or a Google Cloud Storage Bucket.

Material-UI

Material-UI is a React UI framework that implements Google’s Material Design principles in React. It can be added to Gatsby projects in a variety of ways and we’ll see how to use it simply with a plugin.

Netlify/NetlifyCMS

One of the smaller hosting services that works really well with Gatsby is Netlify. Netlify (the company) authored an excellent CMS called NetlifyCMS that makes it really simple to produce/edit/manage content stored in Github. All in all, the combo of GraphQL, Netlify, and NetlifyCMS makes it really simple for developers (who already know React) to build fast websites with an intuitive CMS. NetlifyCMS can be setup so that non-technical users can easily make changes to the content and have Netlify push the changes live. Gone are the days of managing clunky WordPress sites or plugin catastrophes! Also gone are the days of slow loading heavy client side sites (looking at you Soundcloud and Yelp 👀).

Ok, whoah whoah — I’m mostly kidding. The WordPress ecosystem is actually pretty amazing and I use Soundcloud every dang day. What I mean to say is that Gatsby and the entire JAMstack paradigm represent a very exciting evolution in websites that developers will enjoy working on and people will enjoy using.

This tutorial will show you how to setup Gatsby with NetlifyCMS and build out a small demo site (see below). The goal of this tutorial is help give you a better conceptual framework for how Gatsby sites come together. Gatsby already has a very nicely done 8-part tutorial so this tutorial will seek to build upon that and make it even easier to learn Gatsby.

Tutorial Outline:

  • Part 1
    • What We’ll Build
    • About Gatsby (and why try it)
    • Setting up Gatsby
    • A high-level overview of what’s what in Gatsby
    • Understanding Gatsby’s Magic
    • Creating Basic Static Pages with Gatsby
    • Dynamically Creating Pages with gatsby-node.js
    • Creating the About Page
    • Creating the Blog Page and Blog Posts
  • Part 2
    • Setup NetlifyCMS to make editing the content more accessible
    • Create the Courses Page and Individual Courses
    • Add Images and more fields to the Courses and Blogs
    • Style it all with Material-UI

What We’ll Build

This tutorial will be focused on building a very basic clone of the appendTo site (that you’re on right now). This demo site consists of pages for About, Courses, Home, and the Blog. There will also be individual pages for each Course and Blog Post.

The site can be found here: https://appendtostaticstyled.netlify.com/courses

The content in this site lives in a Github repo and can be updated using NetlifyCMS. This gives developers or non-technical users a nice interface for making changes to the content.

About Gatsby (and why try it)

Gatsby is run by VC-backed Berkeley-based Gatsby Inc., which has almost 30 employees (at this time of writing). Many of their founders and employees have ‘making the web fast’ as their Linkedin tagline so it’s fair to say that speed is one Gatsby’s primary selling points. Definitely take a second to try out of some of the sites listed on the Gatsby showcase page. The speed at which an attractive, image-heavy ecommerce site like ShopFlamingo.com loads should inspire you to pick up Gatsby. There’s a pure simple joy in clicking on something and having it load near instantaneously.

The fact that Gatsby is being run as a business and used by large companies should give developers confidence that Gatsby will be around for a while and support will be above average. I find it confidence-inspiring that there are more than 5,000 closed issues on Github.

Furthermore, I received extremely fast help for anything I struggled with while making this post (via Discord, Github, and StackOverflow).

It’s also worth taking a look at some of the blog posts that Gatsby employees have written about their baby. A very interesting one is Making website building fun by founder Kyle Mathews. The whole essay is worth reading and gives you a sense of their founding principles. Mathews describes using the component React-headroom vs. having to implement the same functionality, from scratch, in HTML/CSS/JS (with many more lines). One of the key lines in that essay is this:

What makes technology fun?

This is a complex philosophical question and I’m writing this on a Saturday afternoon so I’ll cheat a bit and just cut the gordian knot by saying “simplicity is fun” and conversely, “complexity is not fun”.

Every one loves new projects. Why? Because they’re simple! We can dive in and experiment and reliably get something done. The more complex the project, the more things seem to break, the more time gets wasted on various yak shaves, and critically, the gap between thinking up an idea and being able to try it grows larger and larger.

Why am I mentioning this bit or the founder at all? Because Gatsby was designed to make building websites more fun. This likely explains the development of their plugin ecosystem and some of the magic and opinions Gatsby has. There’s some upfront difficulty and complexity in learning to play with Gatsby. But once you get it, you’ll probably find it really fun to use.

If you’re still considering other static site options, compare Gatsby with React-static to see how a more manual and less opinionated React-based static site library can look.

And with this background out of the way, let’s start building!

Setting up Gatsby

Gatsby offers a nifty CLI for working with Gatsby projects. As you probably guessed, here’s the terminal command to get it:

npm install -g gatsby-cli

Like many CLIs, typing gatsby –help in the Terminal shows you some of the new commands you can use:

Let’s use gatsby new now to create a new Gatsby project:

gatsby new appendToGatsby

After that build completes, run gatsby develop in the terminal and open http://localhost:8000/ in your browser. Pull the project folder into your text editor of choice.

Take a look at the files and folders generated by the Gatsby CLI. I don’t know about you, but I often feel a bit overwhelmed when I see a whole bunch of new files and folders that a generator has made for me. I sometimes claw through the files frantically trying to figure out what’s what and how it all wires together. To make this easier for you, I’m going to diagram this out.

You should be seeing a folder for components, pages, images and several .js files that live in the src root. Here’s a quick rundown on what they do:

Here’s what you should be seeing:

The hardest thing about Gatsby (for me) was all the little nuances and small details that make up its functionality. For example, with this starter project, I found myself looking for the React-router files and a base app.js. Don’t do this! Gatsby projects work differently than normal Create-React-App projects. Let’s create a new page and learn more.

Take what’s in page-2.js and create a file called coolnewpage.js (in that same /pages folder)

Mine looks something like this:

import React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"

const CoolNewPage = () => (
 <Layout>
   <SEO title="Cool New Page" />
   <h1>Cool New Page</h1>
   <p>Gatsby is Magical but worth learning</p>
   <Link to="/">Go back to the homepage (index.js file)</Link>
 </Layout>
)

export default CoolNewPage

Then re-run gatsby develop in your terminal. Now when I go to http://localhost:8001/coolnewpage, I see this:

Of course this is nothing too special. But consider that you didn’t have to setup the routing or link the components together. Gatsby just detected that a new file was in the pages folder and created the page for it. Try to let some of your React habits go when learning Gatsby (suspend disbelief, if you will). This will make sense with a bit of practice. Let’s now try building something a bit more dynamic.

Building a dynamic About page

Building static pages (by literally placing them in the /pages folder) works fine and would be a good option for really simple ‘brochureware’ sites or a portfolio. But since you’ll likely want to build sites with multiple pages and templates, it makes sense to learn how to use data and templates to build pages dynamically.

We’re next going to build out the About page for this appendTo clone site. Building pages dynamically is quite challenging at first but it’s fairly easy to pick up. Here are the steps:

  1. Create a markdown file (with frontmatter headings) that will hold the page content
  2. Use the Gatsby API methods createPages and onCreateNode to create the page(s) in gatsby-node.js
  3. Create the page template with the appropriate GraphQL query to populate the page with data
  4. Install the appropriate plugins and add them to gatsby-config

It’s hard to understand how these files and APIs connect at first. I’ll walk you through it as slowly and simply as possible.

Step 1: Create the markdown files

Create a markdown file called about.md (that will go in the /pages folder) with the text/info that will go on the about page. Frontmatter (the information between the two triple dashes —) is where you can store fields like the title and the templateKey (which I’ll explain in a bit). Mine looks something like this:

about.md

templateKey: about-page

title: About Page (created with gatsby-node.js)

(This text is obnoxiously red on purpose)

appendTo is your leading source of technical news, tips, and tutorials.

[the rest of the post]

…..

Step 2: Create the pages using the Gatsby API methods in gatsby-node

We need to now create the pages using Gatsby’s createPages and onCreateNode API methods.

const path = require(`path`)
const { createFilePath } = require('gatsby-source-filesystem')

exports.createPages = ({ actions, graphql }) => {
 const { createPage } = actions

 return graphql(`
   {
     allMarkdownRemark(limit: 1000) {
       edges {
         node {
           id
           fields {
             slug
           }
           frontmatter {
             templateKey
           }
         }
       }
     }
   }
 `).then(result => {
   if (result.errors) {
     result.errors.forEach(e => console.error(e.toString()))
     return Promise.reject(result.errors)
   }


   const posts = result.data.allMarkdownRemark.edges

   posts.forEach(edge => {
     const id = edge.node.id
     createPage({
       path: edge.node.fields.slug,
       tags: edge.node.frontmatter.tags,
       component: path.resolve(
         `src/templates/${String(edge.node.frontmatter.templateKey)}.js`
       ),
       // additional data can be passed via context
       context: {
         id
       },
     })
   })
 })
}

 exports.onCreateNode = ({ node, actions, getNode }) => {
   const { createNodeField } = actions
  
    if (node.internal.type === `MarkdownRemark`) {
     const value = createFilePath({ node, getNode, basePath: `pages` })
     createNodeField({
       name: `slug`,
       node,
       value,
     })
   }
 }

Gatsby’s docs say “We do our best to make Gatsby APIs simple to implement.” I think they do an ok job here but it’s still a lot to grok. It doesn’t make sense for me to completely rehash part 7 of their tutorial where they explain this all in great depth. For this tutorial’s sake, I’ll give you the quick version of what’s going on in the code above.

The onCreateNode part below this is for creating the slugs field so that the page urls work properly. Similar to how that coolnewpage.js created a page at /coolnewpage above, this is doing so manually.

In essence, gatsby-node.js is in charge of querying the markdown files and then creating pages (and slugs) using the markdown data and the page templates. Now we need to create the appropriate page template so that this about page can be created.

Step 3: Create the page templates and their GraphQL queries

Next you need to create a /templates folder and a template for this page. My /templates/about.js page looks like this:

import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import Layout from '../components/layout'

const AboutPage = ({ data }) => {
 const { markdownRemark: post } = data

 return (
   <Layout>
     <h1>{post.frontmatter.title}</h1>   
      <p dangerouslySetInnerHTML={{ __html: post.html }} />      
   </Layout>
 )
}

AboutPage.propTypes = {
 data: PropTypes.object.isRequired,
}

export default AboutPage;

export const aboutPageQuery = graphql`
 query AboutPage($id: String!) {
   markdownRemark(id: { eq: $id }) {
     html
     frontmatter {
       title
     }
   }
 }
`

This looks similar to a normal React component, except for the graphql query at the bottom. This query is using the id passed to the context (on gatsby-node.js) to find the appropriate page (where that id matches). It then retrieves the html and the title from that page (aka, the markdown file). Remember this little bit at the bottom of the previous file?

That same ‘id’ is being used in the query right here to get the right page data.

Step 4: Install Plugins

The final thing we need to do is add the right plugins for us to be able to work with the file system and query markdown files.

Terminal

npm install --save gatsby-source-filesystem

npm install --save gatsby-transformer-remark

Within gatsby-config.js, you need to add these plugins into that [plugins array]:

   {
     resolve: `gatsby-source-filesystem`,
     options: {
       name: `src`,
       path: `${__dirname}/src/`,
     },
   },
  ….
   },
...
...
  `gatsby-transformer-remark`,

Then restart the server with gatsby develop and check out the new about page:

The first time doing this can feel a little challenging. There’s a lot of different files being used and it’s pretty easy for things to break. To prevent myself from getting lost in the cognitive overload of Markdown, React, config settings, GraphQL, React context, promises, and nested you-name-its, I came up with mental shorthand for what these files do:

Markdown files: The data that will go into the pages. Easy.

Templates in the /templates folder: React components with GraphQL queries at the bottom used to build the Gatsby static pages.

Gatsby-node.js: Finds my markdown files and creates pages/slugs for them using the right page template.

Gatsby-config.js: Array of plugins and settings I have to touch when installing plugins.

I hope these shorthands help you as you build your mental model of how Gatsby works.

If you need help understanding how to work with GraphQL in Gatsby, Gatsby comes with a built in GraphQL explorer/helper tool called GraphiQL. Gatsby’s tutorial also has a good write up on how to use it.

Creating the Blog Page and Blog Posts

Now that you’ve made an About page, creating other pages is fairly simple. Since appendTo (and the clone we’re building) is primarily a blog page, we’ll now create some blog posts. This involves creating three new files:

  1. /pages/blog.js (the parent /blog page with a list of the blog posts)
  2. /pages/blogs/blog1.md (an example of the markdown files for the blogs)
  3. /components/BlogItem.js (a small component to show the blog excerpt and title on the /blog page)
  4. /templates/single-blog.js (template for just one blog post)

Here’s how I created the blogs:

Step 1: Create blog.js

import React from "react"
import { StaticQuery, graphql } from "gatsby"

import Layout from "../components/layout"
import SEO from "../components/seo"
import BlogItem from "../components/BlogItem"

class BlogPage extends React.Component {
 render() {
   const { data } = this.props
   const { edges: posts } = data.allMarkdownRemark

   return (
     <Layout>
       <SEO title="Blog" />
       <h1>Blog Page</h1>
       <div>
         {posts &&
           posts.map(({ node: post }) => (
             <BlogItem
               key={post.id}
               post={post.frontmatter}
               slug={post.fields.slug}
               excerpt={post.excerpt}
             />
           ))}
       </div>
     </Layout>
   )
 }
}

export default () => (
 <StaticQuery
   query={graphql`
     query BlogPageQuery {
       allMarkdownRemark(
         sort: { order: DESC, fields: [frontmatter___date] }
         filter: { frontmatter: { templateKey: { eq: "single-blog" } } }
       ) {
         edges {
           node {
             excerpt(pruneLength: 40)
             id
             fields {
               slug
             }
             frontmatter {
               title
               templateKey
               date(formatString: "MMMM DD, YYYY")
             }
           }
         }
       }
     }
   `}
   render={data => <BlogPage data={data} />}
 />
)

This page looks similar to our about page. It is a React component with a GraphQL query at the bottom. This Static Query is a Gatsby component that can be used anywhere to query for data. In this case, it is querying for markdown files that have a templateKey of ‘single-blog’ in the frontmatter header. Let’s make these markdown files now.

Step 2: Create markdown blog files

Here’s an example blog I created and filled with hipster ispum. Notice the templateKey line at the top there. That’s what the query above (in my /blog.js file is looking for).

---

templateKey: single-blog

title: blog3

date: 2019-04-10T16:43:29.834Z

description: so stoked on blog3

---

astropub, small batch godard kickstarter sustainable shoreditch raw denim affogato twee. Disrupt normcore lumbersexual, craft beer aesthetic iPhone chambray irony glossier vinyl skateboard tbh fanny pack. Banh mi sartorial hot chicken semiotics roof party PBR&B whatever brunch, kombucha XOXO tumblr helvetica skateboard. Church-key chillwav

Now we need to make the BlogItem.js component that /blog.js can render this data into.

Step 3: Create BlogItem.js

BlogItem.js

import React from "react"
import { Link } from "gatsby"

function BlogItem(props) {
 const { post, slug, excerpt } = props

 return (
   <div>
     <div>
       <Link to={slug}>
         <h1>{post.title}</h1>
       </Link>
       <h3>{post.date}</h3>
       <p>{excerpt}</p>
     </div>
   </div>
 )
}

export default BlogItem

This is a fairly standard React component that uses the Gatsby Link component for linking to other pages.

Restart the development server and you should see this in your browser:

Step 4: Create the single-blog.js template

import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import Layout from '../components/layout'

const BlogPage = ({ data }) => {
  const { markdownRemark: post } = data

  return (
    <Layout>
      <p>{post.frontmatter.title}</p>
       <p> {post.html}  </p>
      />
    </Layout>
  )
}

BlogPage.propTypes = {
  data: PropTypes.object.isRequired,
}

export default BlogPage

export const BlogPageQuery = graphql`
  query BlogPage($id: String!) {
    markdownRemark(id: { eq: $id }) {
      html
      frontmatter {
        title
      }
    }
  }

Clicking on one of the blogs will lead you to this:

To review what’s happening here, the main /blog page is querying for blog markdown files (e.g. blog1.md), then passing this data to itself and rendering a list of blogs using the BlogItem components.

This post covered most of the basics of setting up Gatsby and creating pages manually and automatically using gatsby-node.js. The following post will explore the following:

  • Creating the Courses Page and Individual Courses
  • Installing NetlifyCMS
  • Styling it all with Material-UI

About the Author:

Staticly Typed JavaScript Language and Library Options

December 18th, 2018

Over the last 3-6 years, staticly typed languages and libraries like TypeScript, Flow, and Dart have steadily gained traction in the world of JavaScript web development. More developers, teams, and companies are adopting them every week.

This article will explore why these technologies exist and explore some of the nuances and characteristics of the major ones.

Strong, weak, static and dynamic

One of the first challenges with understanding typing as it relates to web development is understanding the difference between strong, weak, static, and dynamic typing. Strong and static (and weak/dynamic respectively) sometimes get used synonymously. This is incorrect. Yes, JavaScript and PHP are dynamically and weakly typed. But a language like Python is dynamically AND strongly typed. Avoid the tendency to think strong = static. Several great StackOverflow answers clarify the differences between these four terms. I’ll summarize the gist of these:

Static typing means that programs are checked before being executed, and a program might be rejected before it starts. Here’s an example in Java:

String str = "Hello"; // statically typed as string

str = 5; // would throw an error since java is statically typed

Dynamic typing means that you change a variable’s type. You can change the variable’s type of string, for example, to a boolean or integer. The language will let you do that. That is because typing is associated with the value rather than the variable. Here’s an example in Python:

str = "Hello" # it is a string
str = 5 # now it is an integer; perfectly OK

Strong and weak typing, on the other hand, generally refer to something called implicit type conversions. As you were learning JavaScript, you probably remember wacky operations that combine Booleans with integers and strings with nulls like these:

"" + 1 + 0 = "10" // (1)
"" - 1 + 0 = -1 // (2)
true + false = 1
6 / "3" = 2
"2" * "3" = 6
4 + 5 + "px" = "9px"

source: https://javascript.info/task/primitive-conversions-questions

Each of the above are examples of weak typing. JavaScript allows for a very forgiving combination and conversion of different types of variables. This is awesome for flexibility but can cause all sorts of bugs and confusion in the code. Python, on the other hand, is strongly typed, so these implicit type conversions won’t fly.

str = 5 + "hello" # would throw an error since it does not want to cast one type to the other implicitly.

Source: https://stackoverflow.com/a/2351869

Statically typed languages are usually compiled, and dynamically typed languages are usually interpreted. Here are the top 10 TIOBE index languages on a 2×2 matrix of these 4 types of typing:

As you see, some sit the middle as developers point out that they can have a bit of both strong and weak typing (or it can be decided by the developer).

The advantages and disadvantages of weak and dynamic typing

Dynamic typing, free of type annotations, allows for faster prototyping and less verbose code. This is where JavaScript and PHP shine. Eric Elliot lays out the potential disadvantages of static typing quite succinctly:

Type annotations [in static typing] obviously create[s] more syntax noise, and that syntax makes code harder to read, and harder to maintain. But the drawbacks go a little deeper. Specifically, static types can make all of these things harder (not impossible, just more complicated than they need to be):

  • Generic functions & polymorphism
  • Higher order functions
  • Object composition

That’s a drag, because I use all of those things a lot, and if you’re a fluent JavaScript coder, chances are good that you use them a lot, too.

But in exchange for this verbosity, static typing offers many advantages. The biggest advantage is that a whole category of bugs gets detected earlier in the development cycle. These bugs come from the simple mistake of passing the wrong type of variable (e.g. integer instead of string) to the wrong function, loop or class. Because these bugs get detected earlier, it makes it easier to refactor and collaborate on code. In a recently published paper called To Type or Not to Type: Quantifying Detectable Bugs in JavaScript (pdf here), researchers found that 15% of the bugs that end up in committed code could be solved by using static typing. The caveat with that piece is that one of the main authors works for Microsoft (creators of TypeScript). This is not to say the piece is biased, only that the conclusion supports his company’s sponsored language. And so it goes. This is a great place to switch to talking about TypeScript, the most popular static language for front-end development.

TypeScript

TypeScript was launched by Microsoft for public use in October 2012. TypeScript is a superset of JavaScript, making all JavaScript valid TypeScript code. If you’re unfamiliar with supersets, know that Objective-C is a superset of C and Java 7 is a superset of Java 8. TypeScript needs to be compiled to JavaScript (so the browser can read it) using a compiler that is actually written in TypeScript.

A search of Indeed’s job listings shows that 3000+ jobs use the term ‘TypeScript’ (compared to 43000+ that use JavaScript). Google trends shows TypeScript gaining search volume every year since its release.

The core feature of TypeScript is arguably its optional static typing. Here’s an example of how a simple JavaScript function is written with TypeScript static typing:

// JavaScript

function add(x, y) {
  return x + y;
}

// TypeScript

function add(x: number, y: number): number {
  return x + y;
}

Source

You’ll also notice how variable declarations also use the ‘:type’ syntax:

// String
let author: string= "Kyle";
// Number
let age: number = 32;
// Boolean
let writing: boolean = true;
// Date
let orderDate: Date = new Date(2018, 12, 18);

In exchange for the verbosity, we get clear static typing in the examples above. The program won’t compile if the developer slips up and uses the wrong type. These upfront errors save a lot of bugs down the line.

Static typing isn’t the only benefit of TypeScript. Developers also report that it offers a better IDE experience and generally more readable and self-documenting code. Many developers use TypeScript for building React.js applications while others prefer to use Facebook’s flow.

Flow

Flow is a static type checker, designed to quickly find errors (like “Syntax error” and “undefined is not a function”) in JavaScript applications. Flow is not a superset language + compiler, but rather just a code checker. Flow gets called by putting //@flow or /* @flow */ at the top of page that needs checking.

If I try the multiply by a string in the example below, Flow calls me out:

/* @flow */
function timesTwo(x) {
  return x * 2;
}

timesTwo("4");

Flow tells me Cannot perform arithmetic operation because string [1] is not a number.

Try out flow at the Flow.org playground.

The challenge with Flow is that it will allow common things that JavaScript allows like adding a number and a string (using the aforementioned implicit conversions). That’s to say, Flow will block obviously wrong operations but will let others through like so:

// @flow 
function addNumbers(num1, num2) { 
return num1 + num2; 
} 
var x = addNumbers(5, '0'); 
console.log(x); // this will equal 50, which is unlikely to be the right result.

Example in action

This can be fixed by using type annotations (e.g. : number) in Flow. Here’s that example fixed with type annotations:

function addNumbers(num1: number, num2: number) : number {
  return num1 + num2;
}

/* Now Flow barks out
var x = addNumbers(5, '0');
Cannot call `addNumbers` with `'0'` bound to `num2` because string [1] is incompatible with number [2].
*/

Dart

Dart is a strongly and staticly typed language (created by Google) that can be compiled to JavaScript. Dart got some notable press 7+ years ago for trying to kill off JavaScript 😆(Google was, at one point, going to put it into the Chrome engine). Recently, Dart has gotten some new momentum as the Flutter ui builder has gained a lot of traction for building native apps (Flutter is built in Dart and uses Dart). Dart, like Swift and Go, was created by a team of whizkids and experts and is meant to offer the best parts of many languages into one.

While Flow and TypeScript feel fairly similar to JavaScript (or in that realm), Dart looks a bit more like C# or Java. Here’s an example from the Dartlang site.

// Define a function. 
printInteger(int aNumber) { 
print('The number is $aNumber.'); // Print to console. 
} 

// This is where the app starts executing. 
main() { 
var number = 42; // Declare and initialize a variable. 
printInteger(number); // Call a function. 
}

Dart offers some unique typing benefits over Flow or TypeScript. Dart offers static type checking and runtime checks. Types are mandatory but type annotations (e.g. <int>) are optional because Dart performs type inference (it can generally guess the right type).

Why would a developer choose Dart over TypeScript? Many developers/bloggers point out that TypeScript builds upon the advantages/disadvantages of JavaScript. You get the same syntax, data types, and some of the gotchas. Dart, on the other hand, offers a more revolutionary step forward for building fast UIs. Seth Ladd wrote a great list of advantages of Dart over TypeScript:

  • Tree shaking
  • Getters and setters (though I presume TypeScript will get those eventually)
  • Operator overloading
  • Real block scope, no hoisting, no IIFEs
  • A native VM
  • Sane equality semantics
  • No weird implicit conversion craziness
  • Lexically bound this everywhere
  • Mixins
  • Annotations
  • An import system
  • User-defined subscript operators
  • Generics, with reification
  • Mirrors
  • Better collection classes
  • A cleaner DOM API

Should I go strongly and staticly typed? When should I care?

Developer Oliver Zeigermann has a great short list when deciding whether to use a type checker or staticly typed language. If you’re considering going strongly/staticly typed for your next project, run through this checklist:

  • If your project does not live for long: no.
  • If your project is really simple: no.
  • If there is a chance you will need to refactor the thing: yes.
  • If your system is very important or even crucial for the success of your company: yes

For prototyping and playing around, good ol ES5/ES6 are still your go to. But if you’re building things that need to work reliably at scale (and be readable by other developers), it could be worth looking into TypeScript, Flow, or Dart.

 

About the Author:

AirNYT: Firebase Favoriting & Final UI Tweaks

December 6th, 2018

This is the last tutorial in a series called AirNYT, which shows how to the clone the Airbnb search interface to explore NYT travel recommendations. This section of the series will cover:

  • Installing Firebase to allow for user authentication and saving favorites
  • Creating a sign up / login page using Firebase-ui
  • Adding favorite buttons and styling them appropriately according to sign in state
  • Adding a user photo dropdown menu
  • Adding a help-area right-side pop-out Drawer like Airbnb has
  • Setting up toggling of the list vs. map on mobile
  • Creating clickable popup cards on the Map Markers

Repo: https://github.com/kpennell/airnytwithfavorting

Demo: airnytwithfavorting.surge.sh

Installing Firebase to allow for user authentication and saving favorites

As users scroll through these NYT travel recs, I’m hoping some will want an easy to save where they want to go some will want a way to save their favorites. This requires a backend with user authentication. Firebase is a really easy way to do this in React applications. I’m going to show the basic setup for how to let users login and save/retrieve their favorites.

First, install firebase and react-firebaseui using Yarn. Next, setup a basic Firebase project within Firebase (here’s a great tutorial on how to do this).

Next, you’ll need to put the basic config items (given to you by firebase) into your index.js:

Something like this:

 const config = {
    apiKey: "AIzaSyAfdddIPGuz9TTbfVBccKFdwewB0YGNh_M",
    authDomain: "airnyt.firebaseapp.com",
    databaseURL: "https://airnyt.firebaseio.com",
    projectId: "airnyt-2018",
    storageBucket: "airnyt-2018.appspot.com",
    messagingSenderId: "1032396322"
}

// now initialize the firebase app
  const firebaseApp = firebase.initializeApp(config)

Firebase folds fairly easily into React components. The most common way to get and incorporate firebase data into React components is via the lifestyle hook componentDidMount. Here’s an example of this in action:

componentDidMount = () => {
// firebase.auth() is the user authing module. onAuthStateChanged checks if a user is logged in
    firebase.auth().onAuthStateChanged(firebaseUser => {      

/* Here’s what is happening below: If there is a user logged in, call the firebase ref (or part of the JSON tree) where the user’s favorites are. Then loop over the snapshot array of those favorites to make (push) a new array, which will ultimately be saved to state. */

      if (firebaseUser) {
        firebase
          .database()
          .ref("users/" + firebaseUser.uid + "/favorites")
          .on("value", snapshot => {
            let newFavorites = [];
            snapshot.forEach(function(favorite) {
              newFavorites.push({
                id: favorite.key,
                ...favorite.val()
              });
            });
            this.setState({
              user:firebaseUser, // also save the user in state
              favorites: newFavorites
            });
          });
      }
    });
  };

Above is a very common pattern for working with firebase data in React. The parent container gets the data from the firebase ref (a specific part of the JSON tree), saves it in state and passes it to the child components to use. And that’s what we’ll do here for building out this favoriting functionality. Below are the steps I took to build out the Airbnb-esque favorites for this app.

Building a favoriting component (with buttons that style according to whether they are in favorites).

The favoriting component needs empty heart icons and full heart icons, depending on whether the item has been favorited. This component also needs to either add or remove the favorite, depending on whether it is in there or not. The end goal is something like this:

Below is what my FavoritingButton component looks like. Note that this component receives the favorites array and user object (from firebase) as a prop. I’ll comment in the code below to explain what’s going on:

export default class FavoritingButton extends Component {
  addToFavorites = location => {
    if (!this.props.user) {
// If there is no user, open up the login modal (which we’ll build next)
      this.props.toggleLoginSignupModal();

// if there is a user, push the location to their favorites ref in firebase
    } else {
      let userId = this.props.user.uid;
      let favoritesPath = "users/" + userId + "/favorites";  // creating the ref path
      firebase
        .database()
        .ref(favoritesPath)
        .push(location);
      //}
    }
  };

// This one is more complicated at first glance!
// How to remove a favorite
  removeFromFavorites = location => {

    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        firebase
          .database()
          .ref("users/" + firebaseUser.uid + "/favorites")
          .once("value", snapshot => {

/* This is firebase speak for get all of the users’ favorites */
            snapshot.forEach(function(favorite) {
// Loop over the favorites and if the location matches the favorite….
              if (location.pageid === favorite.val().pageid) {
                let favoriteId = favorite.key;
                let favoritesRef = firebase
                  .database()
                  .ref(
                    "users/" + firebaseUser.uid + `/favorites/${favoriteId}`
                  ); // first create a firebase ref to that specific favorite
                favoritesRef.remove(); // Now remove that favorite
              }
            });
          });
      }
    });
  };

/* To sum up the removeFromFavorites, we first have to surgically go into the existing favorites, find the one that needs removing, make a firebase ref for it, then pull it out with the .remove() method. This is the firebasey way of removing data. */

  render() {
    const { favorites, location, classes } = this.props;

/* We need to show an empty or full heart depending on whether that card location is currently in the favorites array. This tests if it is and shows the right icon */
    if (
      favorites.filter(favorite => favorite.pageid === location.pageid)
        .length > 0
    ) {
      return (
        <Favorite
          className={classes.favoriteButtonStyle}
          onClick={() => this.removeFromFavorites(location)}
        />
/* These are each in the material-ui-icons library */
      );
    } else {
      return (
        <FavoriteBorder
          className={classes.emptyFavoriteButtonStyle}
          onClick={() => this.addToFavorites(location)}
        />
      );
    }
  }

I absolute positioned the favoriting heart icons within the LocationCard(s) and styled them a bit.

Built a signup/login modal using firebase-ui

Next, we need a way to login and signup users so they can use these favorite buttons. In keeping with the imitating Airbnb streak, I created a signup/login modal. Like most popup modals, this one will pop open above all the other content and close by clicking outside of it.

The core code for this modal is simple enough:

 <div>
        <Modal
          aria-labelledby="simple-modal-title"
          aria-describedby="simple-modal-description"
          open={this.props.open}
          onClose={this.props.toggleLoginSignupModal}>
          <div style={getModalStyle()} className={classes.paper}>
            <Grid container className={classes.overallContainer}>
              <Grid item xs={5} className={classes.textStuff}>
                <Typography align="center" variant="headline">
                  Please Sign Up or In
                </Typography>
                <Typography align="center" variant="subheading">
                  (To save your favorites)
                </Typography>
              </Grid>
              <Grid item xs={7}>
                <StyledFirebaseAuth
                  uiConfig={this.props.uiConfig}
                  firebaseAuth={firebase.auth()}
                />
              </Grid>
            </Grid>
          </div>
        </Modal>
      </div>

This uses the material-ui Grid to create a simple form page. StyledFirebaseAuth /> is an amazingly simple component given to us by the react-firebaseui library. It creates a nice login component with as many ways to login as we setup (e.g. Github, Facebook). It’s config settings also need to be configured in the index.js like so:

const uiConfig = {
  signInFlow: 'popup',
  signInSuccessUrl: '/',
Google and Email as auth providers.
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
       firebase.auth.EmailAuthProvider.PROVIDER_ID,
  ]
};

But with very little work, I can get some nice login buttons:

I put this modal component as a child in my App.js. Whether it is open or closed will be toggled with a simple function that changes a state value:

// component
      <LoginSignupModal
            open={this.state.LoginSignupModalOpen}
            toggleLoginSignupModal={this.toggleLoginSignupModal}
            uiConfig={this.props.uiConfig}
          />
// toggling function
  toggleLoginSignupModal = () => {
    this.setState({ LoginSignupModalOpen: !this.state.LoginSignupModalOpen });
  };
// default state value
    LoginSignupModalOpen: false,

Hide or Show Menu Items According to Login State

Within Airbnb (and many major sites), the menu will show the user’s face with a dropdown menu if the user is logged in. If the user is logged out, it will show Button/Menu Items like sign up and login.

Let’s set this up now within the AirNYT app.

First, we need to pass some new props to our Header component within App.js:

 <Header
           ...
              user={this.state.user}
              logOut={this.logOut}
              toggleLoginSignupModal={this.toggleLoginSignupModal}

            />

Now, within Header, we need to add a menu and hide/show this menu according to whether user exists. So around login and signup, I wrap the inline conditional test like so:

// If there is no user, show these buttons which will toggle the modal
           {user === null && 
                  <div style={{display:"inline"}}>
                  <Button color="inherit" onClick={this.props.toggleLoginSignupModal}>
                    Sign Up
                  </Button>

                  <Button color="inherit" onClick={this.props.toggleLoginSignupModal}>
                    Log in
                  </Button>
                  </div>
                    }

But what if there is a user? What should I show then? Maybe something like this:

   {user && (
              <div style={{display:"inline"}}>
                <IconButton
                  aria-owns={open ? 'menu-appbar' : undefined}
                  aria-haspopup="true"
                  onClick={this.handleMenu}
                  color="inherit"
                >
         
                  <Avatar alt="user pic" src={user.photoURL} className={classes.avatar} />
                </IconButton>
                <Menu
                  id="menu-appbar"
                  anchorEl={anchorEl}
                  anchorOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  transformOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  open={open}
                  onClose={this.handleClose}
                >
               
                  <MenuItem onClick={this.props.logOut}>Log Out</MenuItem>
                </Menu>
              </div>
            )}

We get a basic little dropdown menu with a logout button. Notice how easy it is to pull in user.photoURL? This is the beauty of firebase auth-ing. Average/intermediate developers can very quickly put a professional touch on their app (like importing a user’s facebook or google photo into a new app). I put a grey border around the Avatar to make it a look a bit more airbnb-ish.

Obviously I skipped a lot of things here like styling and how all the parents and children get wired up, but the gist is all here. Firebase makes it incredibly simple to add a backend and user authing to an app like this.

Adding a help right-side pop-out Drawer like Airbnb has

Airbnb has a popout right-side help drawer on their desktop web app. It features access to common questions:

My guess would be this allows easy access to common questions while also not breaking users out of the buying flow (like if they immediately redirected to the help center). But who knows 🤷‍♂️? Either way, I wanted to show how easy it was to recreate this within material-ui. Here is my simple HelpDrawer component:

class HelpDrawer extends React.Component {
  render() {
    const { classes, open } = this.props;

    return (
      <div>
        <Drawer
          anchor="right"
          open={this.props.open}
          onClose={this.props.toggleDrawer}
          classes={{
                paper: classes.drawer,
              }}

          >
          <div className={classes.toolbar}>
            <Typography variant="h6" component="h2">
              AirNYT Help
            </Typography>
              <IconButton onClick={this.props.toggleDrawer} className={classes.farRightToggleButton}>
                <Close />
               </IconButton>
             
          </div>

          <Divider />
          <div
            tabIndex={0}
            role="button"
            onClick={this.props.toggleDrawer}
            className={classes.content}
            onKeyDown={this.props.toggleDrawer}>
            
            Content goes here
          </div>
        </Drawer>
      </div>
    );
  }
}

Within App.js, my drawer works much like the LoginSignupModal. It sits there and can be toggled open/close with a simple function:

// App.js
 <HelpDrawer toggleDrawer={this.toggleDrawer} open={this.state.drawerOpen} />

// The function
 toggleDrawer = () => {
    this.setState({
      drawerOpen: !this.state.drawerOpen,
    });
  };

And with that, we end up with a nice start for right-side Drawer. I need to cut this tutorial short, but this would an excellent place to show a list of user favorites.

Mobile: toggle map vs. list

Our desktop map vs. list toggling experience matches that of Airbnb and works fine. On a desktop sized screen, the map and list of cards can share the screen. Obviously, this won’t cut it on mobile. And so Airbnb (and many others) allow users to toggle between the map and list like so:

With a bit zIndex trickery and some responsive breakpoints in our CSS, this is actually fairly easily to emulate.

The action will happen within my LocationsGrid.js (where the List and Map live). First, I’ll show you what I accomplished:

To accomplish this, I need a state value and a toggling function

// state
mobileMapShowing: false

// function
  toggleMapAndListOnMobile = () => {
    this.setState({
      mobileMapShowing: !this.state.mobileMapShowing
    })
  }

Now I need a floating action button:

            <Button variant="fab" aria-label="Add" className={classes.fab} onClick={this.toggleMapAndListOnMobile}>
              {this.state.mobileMapShowing ? <Collections /> : <Place /> }        
              </Button>
// That simple ternary will show a different icon depending on whether the mobile map is showing

Now I need to show and hide the map vs. the list. This is done easily with zIndex:

div className={classes.mapDiv} style={ this.state.mobileMapShowing ? {zIndex:4} : {zIndex:1} }>

So, in English, this toggles the zIndex from 1 to 4, depending on whether the value mobileMapShowing is true or false. Within my styles, the list has a higher initial zIndex vs. the map.

mapDiv: {
...
...
    }),
    [theme.breakpoints.down("sm")]: {
      zIndex: 2,
      position: "absolute",
      width: "100%",
    }
  },
  listGridDiv: {
….
    [theme.breakpoints.down("sm")]: {
      justifyContent: "center",
      position: "absolute",
      zIndex: 3,
      background:"white"
    },
  },

And just like that, we have a nice map vs. list toggling functionality on mobile. One button serves to toggle the zIndex of the map, thus hiding/showing it.

Map: Popup Cards on Markers

Airbnb’s map interface features clickable markers that show more info. This can be enormously helpful for exploring geographic data and keeping users from having to hop back and forth between the list and the map. The airbnb cards look something like this:

Here’s how I implement this card within my MapMarker. Within MapAndMarkers, I need to add some props onto the map marker:

         <MapMarker
... 
          clickedMarker={this.state.clickedMarker}
          handleMarkerClick={this.openMarkerPopup}
          closeAllMarkers={this.closeAllMarkers}
          favorites={this.props.favorites}
          toggleLoginSignupModal={this.props.toggleLoginSignupModal}
          user={this.props.user}

I’m adding the user and favorites props so that the FavortingButton will work on the card. handleMarkerClick={this.openMarkerPopup} and closeAllMarkers={this.closeAllMarkers} refer to the following functions:

// sets the state value for which marker is ‘popped up’
  openMarkerPopup = key => {
    this.setState({
      clickedMarker: key
    });
  };
// closes all markers
  closeAllMarkers = () => {
    this.setState({
      clickedMarker: null
    });
  };

Now, within MapMarker.js, there’s a bit of logic going on. It’s actually fairly straightforward: There’s 1 condition for the default marker, 1 condition for the hovered card (which changes the background color on the marker), and 1 condition for the clicked marker (which pop ups a card like interface).

// if hovered on the related card
    if (pageid == hoveredCardId) {
      return (
        <div className={classes.markerParent}>
          <span
            className={classNames(
              classes.tooltips_span,
              classes.niftyHoverBackground
            )}>
            {this.props.name}
          </span>
        </div>
      );
// if clicked
    } else if (pageid == clickedMarker) {
      return (
        <div className={classes.cardParent}>
          <Card className={classes.card}>
            <div className={classes.CarouselDiv}>
              <CardCarousel
                location={location}
                className={classes.CardCarouselImage}
              />
              <FavoritingButton {...this.props} location={location} />
              <Clear
                className={classes.closeButton}
                onClick={this.closeAllMarkers}
              />
            </div>

            <CardContent className={classes.cardContentArea}>
              <Typography noWrap className={classes.yearArea} component="p">
                Featured in:{" "}
                <span className={classes.year}>{location.year}</span> ·{" "}
                <a
                  href={location.article_link}
                  className={classes.articleLink}
                  target="_blank">
                  Original Article <Launch className={classes.launchicon} />
                </a>
              </Typography>

              <Typography variant="h6" component="h2">
                {location.location_name}
              </Typography>
              <div className={classes.snippet_area}>
                <Typography
                  className={classes.snippet_text}
                  noWrap
                  component="p">
                  {location.clean_snippet}
                </Typography>
                <Typography component="p">
                  <a
                    href={location.url}
                    style={{
                      textDecoration: "none",
                      color: "#008489",
                      fontWeight: 600,
                      fontSize: 12
                    }}
                    className={classes.articleLink}
                    target="_blank">
                    Learn More
                  </a>
                </Typography>
              </div>
            </CardContent>
          </Card>
        </div>
      );
// the default, neither hovered nor clicked
    } else {
      return (
        <div className={classes.markerParent} onClick={this.markerClickInChild}>
          <span className={classes.tooltips_span}>{this.props.name}</span>
        </div>
      );
    }

And just like that, we get a fairly intuitive popup card on the map.

Final Thoughts

Thanks for following along with this tutorial. Hopefully it showed you one way of piecing together some components to make an interactive Airbnb-esque map interface. Feel free to submit suggestions and pull requests to the Github repo for this project.

https://github.com/kpennell/airnytwithfavorting

This is the last tutorial in a series called AirNYT, which shows how to the clone the Airbnb search interface to explore NYT travel recommendations. This section of the series will cover:

  • Installing Firebase to allow for user authentication and saving favorites
  • Creating a sign up / login page using Firebase-ui
  • Adding favorite buttons and styling them appropriately according to sign in state
  • Adding a user photo dropdown menu
  • Adding a help-area right-side pop-out Drawer like Airbnb has
  • Setting up toggling of the list vs. map on mobile
  • Creating clickable popup cards on the Map Markers

Repo: https://github.com/kpennell/airnytwithfavorting

Demo: airnytwithfavorting.surge.sh

Installing Firebase to allow for user authentication and saving favorites

As users scroll through these NYT travel recs, I’m hoping some will want an easy to save where they want to go some will want a way to save their favorites. This requires a backend with user authentication. Firebase is a really easy way to do this in React applications. I’m going to show the basic setup for how to let users login and save/retrieve their favorites.

First, install firebase and react-firebaseui using Yarn. Next, setup a basic Firebase project within Firebase (here’s a great tutorial on how to do this).

Next, you’ll need to put the basic config items (given to you by firebase) into your index.js:

Something like this:

 const config = {
    apiKey: "AIzaSyAfdddIPGuz9TTbfVBccKFdwewB0YGNh_M",
    authDomain: "airnyt.firebaseapp.com",
    databaseURL: "https://airnyt.firebaseio.com",
    projectId: "airnyt-2018",
    storageBucket: "airnyt-2018.appspot.com",
    messagingSenderId: "1032396322"
}

// now initialize the firebase app
  const firebaseApp = firebase.initializeApp(config)

Firebase folds fairly easily into React components. The most common way to get and incorporate firebase data into React components is via the lifestyle hook componentDidMount. Here’s an example of this in action:

componentDidMount = () => {
// firebase.auth() is the user authing module. onAuthStateChanged checks if a user is logged in
    firebase.auth().onAuthStateChanged(firebaseUser => {      

/* Here’s what is happening below: If there is a user logged in, call the firebase ref (or part of the JSON tree) where the user’s favorites are. Then loop over the snapshot array of those favorites to make (push) a new array, which will ultimately be saved to state. */

      if (firebaseUser) {
        firebase
          .database()
          .ref("users/" + firebaseUser.uid + "/favorites")
          .on("value", snapshot => {
            let newFavorites = [];
            snapshot.forEach(function(favorite) {
              newFavorites.push({
                id: favorite.key,
                ...favorite.val()
              });
            });
            this.setState({
              user:firebaseUser, // also save the user in state
              favorites: newFavorites
            });
          });
      }
    });
  };

Above is a very common pattern for working with firebase data in React. The parent container gets the data from the firebase ref (a specific part of the JSON tree), saves it in state and passes it to the child components to use. And that’s what we’ll do here for building out this favoriting functionality. Below are the steps I took to build out the Airbnb-esque favorites for this app.

Building a favoriting component (with buttons that style according to whether they are in favorites).

The favoriting component needs empty heart icons and full heart icons, depending on whether the item has been favorited. This component also needs to either add or remove the favorite, depending on whether it is in there or not. The end goal is something like this:

Below is what my FavoritingButton component looks like. Note that this component receives the favorites array and user object (from firebase) as a prop. I’ll comment in the code below to explain what’s going on:

export default class FavoritingButton extends Component {
  addToFavorites = location => {
    if (!this.props.user) {
// If there is no user, open up the login modal (which we’ll build next)
      this.props.toggleLoginSignupModal();

// if there is a user, push the location to their favorites ref in firebase
    } else {
      let userId = this.props.user.uid;
      let favoritesPath = "users/" + userId + "/favorites";  // creating the ref path
      firebase
        .database()
        .ref(favoritesPath)
        .push(location);
      //}
    }
  };

// This one is more complicated at first glance!
// How to remove a favorite
  removeFromFavorites = location => {

    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        firebase
          .database()
          .ref("users/" + firebaseUser.uid + "/favorites")
          .once("value", snapshot => {

/* This is firebase speak for get all of the users’ favorites */
            snapshot.forEach(function(favorite) {
// Loop over the favorites and if the location matches the favorite….
              if (location.pageid === favorite.val().pageid) {
                let favoriteId = favorite.key;
                let favoritesRef = firebase
                  .database()
                  .ref(
                    "users/" + firebaseUser.uid + `/favorites/${favoriteId}`
                  ); // first create a firebase ref to that specific favorite
                favoritesRef.remove(); // Now remove that favorite
              }
            });
          });
      }
    });
  };
/* To sum up the removeFromFavorites, we first have to surgically go into the existing favorites, find the one that needs removing, make a firebase ref for it, then pull it out with the .remove() method. This is the firebasey way of removing data. */

  render() {
    const { favorites, location, classes } = this.props;

/* We need to show an empty or full heart depending on whether that card location is currently in the favorites array. This tests if it is and shows the right icon */
    if (
      favorites.filter(favorite => favorite.pageid === location.pageid)
        .length > 0
    ) {
      return (
        <Favorite
          className={classes.favoriteButtonStyle}
          onClick={() => this.removeFromFavorites(location)}
        />
/* These are each in the material-ui-icons library */
      );
    } else {
      return (
        <FavoriteBorder
          className={classes.emptyFavoriteButtonStyle}
          onClick={() => this.addToFavorites(location)}
        />
      );
    }
  }

I absolute positioned the favoriting heart icons within the LocationCard(s) and styled them a bit.

Built a signup/login modal using firebase-ui

Next, we need a way to login and signup users so they can use these favorite buttons. In keeping with the imitating Airbnb streak, I created a signup/login modal. Like most popup modals, this one will pop open above all the other content and close by clicking outside of it.

The core code for this modal is simple enough:

 <div>
        <Modal
          aria-labelledby="simple-modal-title"
          aria-describedby="simple-modal-description"
          open={this.props.open}
          onClose={this.props.toggleLoginSignupModal}>
          <div style={getModalStyle()} className={classes.paper}>
            <Grid container className={classes.overallContainer}>
              <Grid item xs={5} className={classes.textStuff}>
                <Typography align="center" variant="headline">
                  Please Sign Up or In
                </Typography>
                <Typography align="center" variant="subheading">
                  (To save your favorites)
                </Typography>
              </Grid>
              <Grid item xs={7}>
                <StyledFirebaseAuth
                  uiConfig={this.props.uiConfig}
                  firebaseAuth={firebase.auth()}
                />
              </Grid>
            </Grid>
          </div>
        </Modal>
      </div>

This uses the material-ui Grid to create a simple form page. StyledFirebaseAuth /> is an amazingly simple component given to us by the react-firebaseui library. It creates a nice login component with as many ways to login as we setup (e.g. Github, Facebook). It’s config settings also need to be configured in the index.js like so:

const uiConfig = {
  signInFlow: 'popup',
  signInSuccessUrl: '/',
Google and Email as auth providers.
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
       firebase.auth.EmailAuthProvider.PROVIDER_ID,
  ]
};

But with very little work, I can get some nice login buttons:

I put this modal component as a child in my App.js. Whether it is open or closed will be toggled with a simple function that changes a state value:

// component
      <LoginSignupModal
            open={this.state.LoginSignupModalOpen}
            toggleLoginSignupModal={this.toggleLoginSignupModal}
            uiConfig={this.props.uiConfig}
          />
// toggling function
  toggleLoginSignupModal = () => {
    this.setState({ LoginSignupModalOpen: !this.state.LoginSignupModalOpen });
  };
// default state value
    LoginSignupModalOpen: false,

Hide or Show Menu Items According to Login State

Within Airbnb (and many major sites), the menu will show the user’s face with a dropdown menu if the user is logged in. If the user is logged out, it will show Button/Menu Items like sign up and login.

Let’s set this up now within the AirNYT app.

First, we need to pass some new props to our Header component within App.js:

 <Header
           ...
              user={this.state.user}
              logOut={this.logOut}
              toggleLoginSignupModal={this.toggleLoginSignupModal}

            />

Now, within Header, we need to add a menu and hide/show this menu according to whether user exists. So around login and signup, I wrap the inline conditional test like so:

// If there is no user, show these buttons which will toggle the modal
           {user === null && 
                  <div style={{display:"inline"}}>
                  <Button color="inherit" onClick={this.props.toggleLoginSignupModal}>
                    Sign Up
                  </Button>

                  <Button color="inherit" onClick={this.props.toggleLoginSignupModal}>
                    Log in
                  </Button>
                  </div>
                    }

But what if there is a user? What should I show then? Maybe something like this:

{user && (
              <div style={{display:"inline"}}>
                <IconButton
                  aria-owns={open ? 'menu-appbar' : undefined}
                  aria-haspopup="true"
                  onClick={this.handleMenu}
                  color="inherit"
                >
         
                  <Avatar alt="user pic" src={user.photoURL} className={classes.avatar} />
                </IconButton>
                <Menu
                  id="menu-appbar"
                  anchorEl={anchorEl}
                  anchorOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  transformOrigin={{
                    vertical: 'top',
                    horizontal: 'right',
                  }}
                  open={open}
                  onClose={this.handleClose}
                >
               
                  <MenuItem onClick={this.props.logOut}>Log Out</MenuItem>
                </Menu>
              </div>
            )}

We get a basic little dropdown menu with a logout button. Notice how easy it is to pull in user.photoURL? This is the beauty of firebase auth-ing. Average/intermediate developers can very quickly put a professional touch on their app (like importing a user’s facebook or google photo into a new app). I put a grey border around the Avatar to make it a look a bit more airbnb-ish.

Obviously I skipped a lot of things here like styling and how all the parents and children get wired up, but the gist is all here. Firebase makes it incredibly simple to add a backend and user authing to an app like this.

Adding a help right-side pop-out Drawer like Airbnb has

Airbnb has a popout right-side help drawer on their desktop web app. It features access to common questions:

My guess would be this allows easy access to common questions while also not breaking users out of the buying flow (like if they immediately redirected to the help center). But who knows 🤷‍♂️? Either way, I wanted to show how easy it was to recreate this within material-ui. Here is my simple HelpDrawer component:

class HelpDrawer extends React.Component {
  render() {
    const { classes, open } = this.props;

    return (
      <div>
        <Drawer
          anchor="right"
          open={this.props.open}
          onClose={this.props.toggleDrawer}
          classes={{
                paper: classes.drawer,
              }}

          >
          <div className={classes.toolbar}>
            <Typography variant="h6" component="h2">
              AirNYT Help
            </Typography>
              <IconButton onClick={this.props.toggleDrawer} className={classes.farRightToggleButton}>
                <Close />
               </IconButton>
             
          </div>

          <Divider />
          <div
            tabIndex={0}
            role="button"
            onClick={this.props.toggleDrawer}
            className={classes.content}
            onKeyDown={this.props.toggleDrawer}>
            
            Content goes here
          </div>
        </Drawer>
      </div>
    );
  }
}

Within App.js, my drawer works much like the LoginSignupModal. It sits there and can be toggled open/close with a simple function:

// App.js
 <HelpDrawer toggleDrawer={this.toggleDrawer} open={this.state.drawerOpen} />

// The function
 toggleDrawer = () => {
    this.setState({
      drawerOpen: !this.state.drawerOpen,
    });
  };

And with that, we end up with a nice start for right-side Drawer. I need to cut this tutorial short, but this would an excellent place to show a list of user favorites.

Mobile: toggle map vs. list

Our desktop map vs. list toggling experience matches that of Airbnb and works fine. On a desktop sized screen, the map and list of cards can share the screen. Obviously, this won’t cut it on mobile. And so Airbnb (and many others) allow users to toggle between the map and list like so:

With a bit zIndex trickery and some responsive breakpoints in our CSS, this is actually fairly easily to emulate.

The action will happen within my LocationsGrid.js (where the List and Map live). First, I’ll show you what I accomplished:

To accomplish this, I need a state value and a toggling function

// state
mobileMapShowing: false

// function
  toggleMapAndListOnMobile = () => {
    this.setState({
      mobileMapShowing: !this.state.mobileMapShowing
    })
  }

Now I need a floating action button:

 <Button variant="fab" aria-label="Add" className={classes.fab} onClick={this.toggleMapAndListOnMobile}>
              {this.state.mobileMapShowing ? <Collections /> : <Place /> }        
              </Button>
// That simple ternary will show a different icon depending on whether the mobile map is showing

Now I need to show and hide the map vs. the list. This is done easily with zIndex:

<div className={classes.mapDiv} style={ this.state.mobileMapShowing ? {zIndex:4} : {zIndex:1}  }>

So, in English, this toggles the zIndex from 1 to 4, depending on whether the value mobileMapShowing is true or false. Within my styles, the list has a higher initial zIndex vs. the map.

  mapDiv: {
...
...
    }),
    [theme.breakpoints.down("sm")]: {
      zIndex: 2,
      position: "absolute",
      width: "100%",
    }
  },
  listGridDiv: {
….
    [theme.breakpoints.down("sm")]: {
      justifyContent: "center",
      position: "absolute",
      zIndex: 3,
      background:"white"
    },
  },

And just like that, we have a nice map vs. list toggling functionality on mobile. One button serves to toggle the zIndex of the map, thus hiding/showing it.

Map: Popup Cards on Markers

Airbnb’s map interface features clickable markers that show more info. This can be enormously helpful for exploring geographic data and keeping users from having to hop back and forth between the list and the map. The airbnb cards look something like this:

Here’s how I implement this card within my MapMarker. Within MapAndMarkers, I need to add some props onto the map marker:

      <MapMarker
... 
          clickedMarker={this.state.clickedMarker}
          handleMarkerClick={this.openMarkerPopup}
          closeAllMarkers={this.closeAllMarkers}
          favorites={this.props.favorites}
          toggleLoginSignupModal={this.props.toggleLoginSignupModal}
          user={this.props.user} />

I’m adding the user and favorites props so that the FavortingButton will work on the card. handleMarkerClick={this.openMarkerPopup} and closeAllMarkers={this.closeAllMarkers} refer to the following functions:

// sets the state value for which marker is ‘popped up’
  openMarkerPopup = key => {
    this.setState({
      clickedMarker: key
    });
  };
// closes all markers
  closeAllMarkers = () => {
    this.setState({
      clickedMarker: null
    });
  };

Now, within MapMarker.js, there’s a bit of logic going on. It’s actually fairly straightforward: There’s 1 condition for the default marker, 1 condition for the hovered card (which changes the background color on the marker), and 1 condition for the clicked marker (which pop ups a card like interface).

// if hovered on the related card
    if (pageid == hoveredCardId) {
      return (
        <div className={classes.markerParent}>
          <span
            className={classNames(
              classes.tooltips_span,
              classes.niftyHoverBackground
            )}>
            {this.props.name}
          </span>
        </div>
      );
// if clicked
    } else if (pageid == clickedMarker) {
      return (
        <div className={classes.cardParent}>
          <Card className={classes.card}>
            <div className={classes.CarouselDiv}>
              <CardCarousel
                location={location}
                className={classes.CardCarouselImage}
              />
              <FavoritingButton {...this.props} location={location} />
              <Clear
                className={classes.closeButton}
                onClick={this.closeAllMarkers}
              />
            </div>

            <CardContent className={classes.cardContentArea}>
              <Typography noWrap className={classes.yearArea} component="p">
                Featured in:{" "}
                <span className={classes.year}>{location.year}</span> ·{" "}
                <a
                  href={location.article_link}
                  className={classes.articleLink}
                  target="_blank">
                  Original Article <Launch className={classes.launchicon} />
                </a>
              </Typography>

              <Typography variant="h6" component="h2">
                {location.location_name}
              </Typography>
              <div className={classes.snippet_area}>
                <Typography
                  className={classes.snippet_text}
                  noWrap
                  component="p">
                  {location.clean_snippet}
                </Typography>
                <Typography component="p">
                  <a
                    href={location.url}
                    style={{
                      textDecoration: "none",
                      color: "#008489",
                      fontWeight: 600,
                      fontSize: 12
                    }}
                    className={classes.articleLink}
                    target="_blank">
                    Learn More
                  </a>
                </Typography>
              </div>
            </CardContent>
          </Card>
        </div>
      );
// the default, neither hovered nor clicked
    } else {
      return (
        <div className={classes.markerParent} onClick={this.markerClickInChild}>
          <span className={classes.tooltips_span}>{this.props.name}</span>
        </div>
      );
    }

And just like that, we get a fairly intuitive popup card on the map.

Final Thoughts

Thanks for following along with this tutorial. Hopefully it showed you one way of piecing together some components to make an interactive Airbnb-esque map interface. Feel free to submit suggestions and pull requests to the Github repo for this project.

https://github.com/kpennell/airnytwithfavorting

About the Author:

AirNYT: Pagination + Filtering + Responsiveness

November 27th, 2018

This tutorial picks up where we left off around building the map and markers. This is part of a larger tutorial series on cloning the Airbnb map and cards interface to be able to explore the last 7 years of New York Times travel recommendations. The short name for this app/series is AirNYT.
In this part of the tutorial, we will continue building out the following:

  • Working Pagination to make exploring the data easier/faster
  • A popup year filter that allows users to show NYT data by year
  • Text/Search Filtering to allow for string query filtering of the data
  • A responsive menu
  • General responsible responsiveness to make this app mobile-friendly

Our end goal is this: http://airnyt.surge.sh

Building working pagination to make exploring the data easier

If you play around with the Airbnb interface as much as I have, you’ll notice that they use infinite scroll when the map is hidden and pagination when the map is showing. This makes perfect sense, from the user’s perspective, as the map should only display a subset of the total properties. Well, you might be able to make some sort of cool infinite scroll updating map, but I don’t think most user would find this intuitive. I mention this background so as to say: we need pagination.
If Github stars are a proxy for popularity, then most React developers are using react-paginate for their pagination. Well, I tried and tried to like and use react-paginate but I found it lacking on the docs and props front. It felt sort of heavy and clunky and Angular 1-ey to me. After some Googling, I came across react-paginating. I found it’s API and examples much easier to understand so I went with this.
To achieve basic client-side pagination, we need two things:

  1. A pagination ui with next buttons and page numbers
  2. To appropriately slice our big array down to only display a subset of it on the appropriate page

This was achieved fairly easily with the following code:
I first needed to calculate a variety of values within my LocationsGrid component. I’ll comment what each of them do:

const { currentPage } = this.state; // a state variable that tracks which page the user is on.
const resultsPerPage = 30; // how many results I’ll display
const pageCount = Math.ceil(locations.length / resultsPerPage); // quantity of pages
const total = Math.ceil(locations.length); // total number of values
const offset = (currentPage - 1) * resultsPerPage; // the specific area of my area I need to slice out for that page
const locationsSlicedDownOnPage = locations.slice(
  offset,
  offset + resultsPerPage
); // a subset of my locations array to be displayed on the page

The following simple function changes the page:

handlePageChange = page => {
  this.setState({
    currentPage: page
  });
};

As you can see, with very little code, we can calculate the appropriate props to give to our PaginationComponent:

// LocationsGrid.js
<PaginationComponent
  total={total}
  resultsPerPage={resultsPerPage}
  pageCount={pageCount}
  currentPage={currentPage}
  handlePageChange={this.handlePageChange}
  offset={offset}
/>;

The pagination component has a bit more going on, but it’s easy to figure out with some explaining. First, take a look a what we’re making:

Here’s the code:

const PaginationComponent = ({
  total,
  resultsPerPage,
  pageCount,
  currentPage,
  handlePageChange,
  offset
}) => {
  return (
    <Pagination
      total={total}
      limit={resultsPerPage}
      pageCount={pageCount}
      currentPage={currentPage}
      offset={Math.ceil(offset)}
      resultsPerPage={Math.ceil(resultsPerPage)}
    >
      {({
        pages,
        currentPage,
        hasNextPage,
        hasPreviousPage,
        previousPage,
        nextPage,
        totalPages,
        getPageItemProps
      }) => (
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            alignItems: "center"
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "space-evenly",
              alignItems: "center",
              width: "300px"
            }}
          >
            {hasPreviousPage && (
              <NavigateBefore
                style={{
                  border: "1px solid #008489 ",
                  borderRadius: "50%",
                  color: "#008489"
                }}
                {...getPageItemProps({
                  pageValue: previousPage,
                  onPageChange: handlePageChange
                })}
              >
                {"<"}
              </NavigateBefore>
            )}
            {pages.map(page => {
              let activePage = { color: "#008489", cursor: "pointer" };
              if (currentPage === page) {
                activePage = {
                  border: "1px solid #008489 ",
                  borderRadius: "50%",
                  color: "#008489",
                  borderRadius: "50%",
                  width: "25px",
                  height: "25px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  backgroundColor: "#008489",
                  color: "white"
                };
              }
              if (
                page < currentPage + 3 &&
                page > currentPage - 3 &&
                page != totalPages
              ) {
                return (
                  <Typography
                    variant="subtitle2"
                    gutterBottom
                    key={page}
                    style={activePage}
                    {...getPageItemProps({
                      pageValue: page,
                      onPageChange: handlePageChange
                    })}
                  >
                    {page}
                  </Typography>
                );
              }
            })}
            <span>...</span>
            {pages.map(page => {
              let activePage = null;
              if (currentPage === page) {
                activePage = {
                  border: "1px solid #008489 ",
                  borderRadius: "50%",
                  color: "#008489",
                  cursor: "pointer"
                };
              }
              if (page > totalPages - 1) {
                return (
                  <Typography
                    variant="subtitle2"
                    gutterBottom
                    key={page}
                    style={activePage}
                    style={{
                      color: "#008489",
                      cursor: "pointer"
                    }}
                    {...getPageItemProps({
                      pageValue: page,
                      onPageChange: handlePageChange
                    })}
                  >
                    {page}
                  </Typography>
                );
              }
            })}
            {hasNextPage && (
              <NavigateNext
                {...getPageItemProps({
                  pageValue: nextPage,
                  onPageChange: handlePageChange
                })}
                style={{
                  border: "1px solid #008489 ",
                  borderRadius: "50%",
                  color: "#008489",
                  cursor: "pointer"
                }}
              >
                {">"}
              </NavigateNext>
            )}
          </div>

          <div>
            <Typography variant="caption" gutterBottom>
              {offset} - {offset + resultsPerPage} of {total} Locations
            </Typography>
          </div>
        </div>
      )}
    </Pagination>
  );
};

export default PaginationComponent;

I’ll break down what’s happening. Our pagination needs a previous and next arrows. Those are created using the material-ui icons (NavigateBefore and NavigateNext). We need a subset of pages to display, then an ellipsis …, followed by the last page. That’s what all of those pages.map are accomplishing.
The page < currentPage + 3 && page > currentPage – 3 && page != totalPages part is getting a very specific subset of the pages to display to user. In English, this says “show them a few behind the current page, a few ahead of the current page, but not the last page!”.
The section at the bottom of the code is telling the user how many of the listings they are seeing:


It’s a fair amount of code, but it ultimately adds up to a component that is pretty close the Airbnb version.
Airbnb’s:

AirNYT’s

Boo-yah!

A client-side year filter that allows users to show NYT data by year

I really like the way Airbnb gives users a ton of different filters without cluttering up their ui. Their filter bar features buttons that queue popovers/modals to achieve this.

I mimicked this using Material-ui’s Popover component. Here’s how I created a filter that allows user to filter out different years from the total results.

// FilterPopup.js
<div className={classes.FilterPopup}>
  <Button
    className={this.state.buttonActive ? classes.active : classes.inactive}
    // toggle the active class to change the color of the button
    onClick={this.handleClick}
    variant="outlined" // conveniently built-in button variant
  >
    Year
  </Button>
  <Popover
    id="simple-popper"
    open={open}
    anchorEl={anchorEl}
    onClose={this.handleClose}
    className={classes.popover}
    PaperProps={{ classes: { root: classes.rightPaper } }}
    BackdropProps={{
      classes: {
        root: classes.backDropStyling // this styling creates the background change to make the popover more pronounced
      }
    }}
  >
    <Card className={classes.card}>
      <CardContent className={classes.cardcontent}>
        <ChipFilter // popover contains the ChipFilter which is where the actual filtering will take place
          years={this.props.years}
          toggleChipProperty={this.props.toggleChipProperty}
          clearAllChips={this.props.clearAllChips}
          selectAllChips={this.props.selectAllChips}
        />
      </CardContent>
    </Card>
  </Popover>
</div>;

ChipFilter is a component that allows users to click the years to toggle them on and off (and thus achieve this client-side filtering):

// ChipFilter.js
<div className={classes.root}>
  <div className={classes.chipSection}>
    // map over the years array and style them according to whether they are
    toggled on or off
    {this.props.years.map((year, index) => {
      return (
        <span
          key={index}
          onClick={this.props.toggleChipProperty(year.key)}
          className={year.showing ? classes.active : classes.inactive}
        >
          {year.label}{" "}
        </span>
      );
    })}
  </div>
  // A simple way to select or deselect all
  <div className={classes.buttonSection}>
    <Button
      variant="outlined"
      color="ternary"
      onClick={this.props.clearAllChips}
      className={classes.button}
    >
      Deselect All
    </Button>
    <Button
      variant="outlined"
      color="ternary"
      onClick={this.props.selectAllChips}
      className={classes.button}
    >
      Select All
    </Button>
  </div>
</div>;

But how does the actual filtering itself happen? That takes place within our App.js:
State.years is an array of objects with key, label, and showing properties:

years: [
  {
    key: 0,
    label: 2011,
    showing: true
  },
  {
    key: 1,
    label: 2012,
    showing: true
  },
  {
    key: 2,
    label: 2013,
    showing: true
  }...
];

matchChipsAndTags is the filtering function that determines whether the location’s year matches up with the state.year’s object showing property. It does this with some ES6 kungfu:

const matchChipsAndTags = function(chips, year) {
  return chips.some(function(chip) {
    return year === chip.label && chip.showing === true;
  });
};

🤔
This function takes the state.chips and the location.year as its parameters. Array.prototype().some is a newer array prototype function that stops executing once a truthy value has been found. So, in English, this function is returning true or false depending on whether that specific locations year property matches the currently showing chips.
So, for instance, a Card/Location like Istanbul will only get rendered (aka appear) if its year property (2013) is matches the chip.label of 2013 (it will) and is that particular chip’s showing property (within state) is true.

Ultimately, the array is filtered down like so:

let filteredlocations = textfilteredlocations.filter(location =>
  matchChipsAndTags(this.state.years, location.year)
);

Text/Search Filtering to allow for string queries of the data

Airbnb has a search box in their header that allows for easy searching of places/experiences:

We’re not going to recreate the whole server-side search experience/function here but I think some client-side filtering would work nicely. This is very easy to do in React.
First, within state in App.js, I’ll declare the search/string value:

filterValue: ""

I’ll then declare a function in App.js to change this value:

handleSearch = e => {
  this.setState({ filterValue: e.target.value });
};

I’ll pass this function as a prop to my Header component. Within component, I’ll call the function within an InputBase component:

const { classes, handleSearch } = this.props;
<InputBase
  placeholder="Filter Places..."
  type="search"
  onChange={handleSearch}
  classes={{
    root: classes.inputRoot,
    input: classes.inputInput
  }}
/>;

I use InputBase instead of TextField so as to avoid any of the default TextField styling (it underlines the search box). TextField is a component composed of several other underlying component, including InputBase.

This search filter box isn’t the most interesting component, but I did find it useful for doing country searches. It was fun to see when different places in the same country got that sweet NYT mention. Here’s what Mexico/Australia look like:

As you see, with New Mexico popping up in a Mexico, it would take some work and data formatting/reorganizing (e.g. a country property in the dataset) to make this truly a country only search. I would also love to have a continent search, but that’s for another tutorial.

A responsive menu

Airbnb’s menu crunches down into a full-screen mobile dropdown on mobile. This frees up a lot of space and only shows the user what they need to see. Here’s how we can achieve the same thing with material-ui.
Material-ui has a really helpful CSS in JSS API for handling breakpoints. You put the breakpoints right into your styles like so:

[theme.breakpoints.up('lg')]: {
   backgroundColor: green[500],
},

This translates to: large size screens and up will have this background style.

[theme.breakpoints.down('sm')]: {
backgroundColor: theme.palette.secondary.main,
},

This would translate to: all the way down to the small size of screen will have this style.
You can set your breakpoints accordingly when you define your theme (usually in index.js or app.js) using createMuiTheme.
To achieve something like the airbnb mobile menu, I’ll first hide the normal menu items on small screens with this styling:

menuItems:{
[theme.breakpoints.down('sm')]: {
display:"none"
},

I’m going to create a dropdown menu, but first I’ll put the styling in for it:

dropdownMenu:{
[theme.breakpoints.up('md')]: { // for mid-size screens and up, please hide this !
display:"none"
},

I then create a DropDownMenu component like so:

class DropDownMenu extends React.Component {
  state = {
    anchorEl: null
  };
  handleClick = event => {
    this.setState({ anchorEl: event.currentTarget });
  };
  handleClose = () => {
    this.setState({ anchorEl: null });
  };
  render() {
    const { anchorEl } = this.state;
    const { classes } = this.props;
    const open = Boolean(anchorEl);
    return (
      <div className={classes.DropDownMenuRoot}>
        <IconButton
          aria-label="More"
          aria-owns={open ? "long-menu" : undefined}
          aria-haspopup="true"
          onClick={this.handleClick}
          className={classes.downCarrotButton}
        >
          <KeyboardArrowDown />
        </IconButton>
        <Menu
          id="long-menu"
          anchorEl={anchorEl}
          open={open}
          onClose={this.handleClose}
          PaperProps={{
            style: {
              maxHeight: ITEM_HEIGHT * 4.5,
              width: 200
            }
          }}
        >
          <MenuItem className={classes.menubuttons} color="inherit">
            Help
          </MenuItem>
          <MenuItem className={classes.menubuttons} color="inherit">
            Sign Up
          </MenuItem>
          <MenuItem className={classes.menubuttons} color="inherit">
            Log in
          </MenuItem>
        </Menu>
      </div>
    );
  }
}

This creates a little popover menu that is toggled using the down arrow next to the logo. It’s not the elegant full-screen menu that airbnb offers, but it’s definitely a good start.
To make this app more generally functional and appealing on mobile, I went through and made small tweaks in the styling using these same theme breakpoint helpers.

To do

This a fun little map + cards + filtering app. But there’s still work to be done. These are the items I’d like to cover in future tutorials:

  • Mobile Map Toggling

Right now, I’m hiding the map div on mobile. Lame! Airbnb has a nice way of toggling the mobile map vs. the cards/list using a little hovering button in the lower right corner of the screen. With a material-ui floating action button and some clever breakpoints and styling, we can make the map available on mobile.

  • Accounts and Favoriting

I’ll show how to incorporate firebase into this app to allow for user authentication and letting people save their favorite places.

  • Infinite Scroll on Cards View and Pagination on Map View

We made a really nice react-virtualized fast loading list in a previous tut. There’s no reason we can’t show this infinite loading list when the map isn’t visible and show the paginated list when the map is showing. We can get the best of both worlds this way.

  • Small ui tweaks

The list should scroll to the top when the page is changed. It could be helpful to center the map on the appropriate map marker when a user hovers on a card.

  • Pop Up Card on the Marker

Airbnb’s map markers show a little pop up card when you click on them. This gives you more info about the place and is quite useful. I’ll add these in a future tutorial.

Stay tuned for more tutorials and the coming end of this tutorial!

About the Author:

AirNYT: Building the Map and Markers Interactivity

November 19th, 2018

This tutorial is a part of a larger tutorial series on cloning the Airbnb map/cards interface to be able to explore the last 7 years of New York Times travel recommendations. The short name for this app/series is AirNYT.

In this part of the tutorial, we will continue building out the various components that make up this map and cards interface.

This specific tutorial will cover how to turn this:

http://nytrecsalaairbnb.surge.sh

…into this:

http://airnyt.surge.sh

To do this, I’ll show you how I built out the following functionality:

  • A carousel slideshow on each card for each location
  • A interactive map with map markers that can be hidden/shown with a toggle switch
  • Hover events on cards that change styling on the map markers

There’s a lot to cover in this tutorial and I’ll try to skip as much boilerplate, yarn installations, and styling as possible when I’m showing how the different parts are coded. If you’d like to see the complete code, you can do so here:

https://github.com/kpennell/airnyt

A carousel slideshow on each card for each location

As you’ve likely seen, Airbnb property listings have these really elegant slideshows on each property:

These let you get the jist of the place without going to that page. To recreate that functionality in the AirNYT app, I’m going to use the React-slick library. This is a React version of the very popular Slick Carousel library.

The react-slick API was fairly straightforward to use. I created a separate CardCarousel component to house it. The component is a simple Slider component that rotates through different material-ui CardMedia images from my data.

class CardCarousel extends React.Component {
  render() {
    const { classes, location } = this.props;

    return (
      <div>
        <Slider {...settings}>
          <div>
            <CardMedia
              component="img"
              className={classes.media}
              image={location.image1}
            />
          </div>
          {location.image2 && (
            <div>
              <CardMedia
                component="img"
                className={classes.media}
                image={location.image2}
              />
            </div>
          )}
          {location.image3 && (
            <div>
              <CardMedia
                component="img"
                className={classes.media}
                image={location.image3}
              />
            </div>
          )}{" "}
        </Slider>
      </div>
    );
  }
}

To mimic the chevron right and left arrows from the Airbnb slider, I put these custom arrows in using material-ui icons:

function SampleNextArrow(props) {
  const {
    className,
    style,
    onClick
  } = props;
  return (
    <ChevronRight
      className={className}
      style={{
        ...style,
        display: "block",
        color: "white",
        fontSize: "3em",
        right: "9px",
        zIndex: 1
      }}
      onClick={onClick}
    />
  );
}
function SamplePrevArrow(props) {
  const {
    className,
    style,
    onClick
  } = props;
  return (
    <ChevronLeft
      className={className}
      style={{
        ...style,
        display: "block",
        color: "white",
        fontSize: "3em",
        left: "9px",
        zIndex: 1
      }}
      onClick={onClick}
    />
  );
}

Within the settings, I can tell the Slider component that I’d like to use these arrow components:

const settings = {
dots: true,
infinite: true,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
nextArrow: <SampleNextArrow />,
prevArrow: <SamplePrevArrow />,

And voila, I have working sliders on all of my cards:

The one caveat I’d share about these sliders is that they definitely slow down the interface. We saw how fast React-virtualized made loading the 380+ cards in the last blog post. But now, each card is loading 3 images, and the lag is noticeable. To solve this, I’d recommend trying out some sort of virtualized or windowed slider that only loads the image when someone opens it or slides to it. But that being said, as long as we’re paginating these results (card listings), the lag shouldn’t be too terrible.

An interactive map with map markers

Maps are perhaps the original data visualization. For spatial or location data, a map is indispensable for visualizing the data. Airbnb has a really well-designed map that can be toggled with a simple switch and we can mimic this fairly easily.

But first, we need a mapping library! The gargantuan React ecosystem offers many options, both in terms of how they are loaded, how they are interacted with, and which tiles (e.g. Google, OSM) get loaded. I’ve tried several and have kept coming back to google-map-react. This library allows React developers to load any component as a marker on a Google map. I like how this library feels like a react-specific way of doing things (a la ‘everything is a component’) and it seems to get out of my way. If you wish to tweak things on the actual Google Maps JavaScript API, google-map-react gives you a simple API to do so.

My MapAndMarkers component is fairly straightforward. I’ll explain how it works after this code snippet:

class MapAndMarkers extends React.Component {
  static defaultProps = {
    center: {
      lat: 30,
      lng: -30
    },
    zoom: 0
  };
  render() {
    const {
      classes,
      locations,
      hoveredCardId,
      pageid
    } = this.props;
    let MapMarkers = locations.map(
      (location, index) => {
        return (
          <MapMarker
            key={location.id}
            lat={location.lat}
            lng={location.lng}
            name={
              location.location_name
            }
            pageid={location.pageid}
            hoveredCardId={
              hoveredCardId
            }
          />
        );
      }
    );
    return (
      <div
        style={{
          width: "100%",
          height: "100%"
        }}
      >
        <GoogleMapReact
          bootstrapURLKeys={{
            key:
              "AIzaSysBBvQLsewI7BPpXln_Jzl_tIUVsH1f775C7GXM",
            v: "3.31"
          }}
          defaultCenter={
            this.props.center
          }
          defaultZoom={this.props.zoom}
          hoverDistance={20 / 2}
          options={createMapOptions}
        >
          {MapMarkers}
        </GoogleMapReact>
      </div>
    );
  }
}

GoogleMapReact is the primary google-map-react component here, and it needs some props and children to work. The required props include the API keys and center and zoom. Center and zoom tell the map which tiles to load. The options prop allows for controlling the aforementioned underlying Google JavaScript API. Things like panning, zooming, controls, etc. get controlled with this object. hoverDistance allows for controlling how far/close to a marker counts as mouse hovering.

To create the {MapMarkers} children, I .map over the locations array prop (my cards/locations data) and pass things like key, lat, and lng as props to the MapMarkers(s). These props tell GoogleMapReact where to render these components/points/markers. I’ll explain the hoveredCardId prop within the context of my MapMarker component.

My MapMarker component is fairly straightforward. The goal was to mimic the plain white tooltips that Airbnb uses:

I used CSS arrow please to create the CSS for this component and used this CSS to React tool to ‘JSSify’ my CSS. There are a variety of nifty React tooltip libraries out there, but I went this route to keep the map fast and have one less dependency.

class MapMarker extends React.Component {
  render() {
    const {
      classes,
      pageid,
      hoveredCardId
    } = this.props;

    return (
      <div
        className={classes.markerParent}
      >
        <span
          className={classNames(
            classes.tooltips_span,
            pageid == hoveredCardId &&
              classes.niftyHoverBackground
          )}
        >
          {this.props.name}
        </span>
      </div>
    );
  }
}

When someone hovers on a Card in the list, I want the MapMarker background to turn purple, like Airbnb does:

To achieve this, I used the classNames library to toggle the class with the background color. So, if the id from the card (that is being hovered upon) is equal to id on the marker, the style changes. To set this id, I setup some functions to be called by mouse events:

// LocationCards.js

<Card className={classes.card} onMouseEnter={e => this.props.c(location)} onMouseLeave={e => this.props.resetCardMarkerHover()} >

setCardMarkerHover is a straightforward function that updates the state variable of hoveredCardId according to the card that is being hovered upon.

// LocationsGrid.js

setCardMarkerHover = location => {
  this.setState({
    hoveredCardId: location.pageid
  });
};

I know I’m skipping some of the steps here but please read through the code if you’d like to see how the state/props variables work here.

Toggle-able Map

Like I mentioned, I really like how Airbnb lets users toggle the map.

Sometimes you want a map and sometimes you just want a grid of cards (and more screen real estate). To recreate this functionality, I put a toggle switch in my FilterBar, like so:

import Switch from "@material-ui/core/Switch";
<FormGroup row>
  <FormControlLabel
    control={
      <Switch
        checked={this.props.mapShowing}
        onChange={
          this.props.toggleMapShowing
        }
        classes={{
          switchBase:
            classes.AirBnbSwitchBase,
          bar: classes.AirBnbBar,
          icon: classes.AirBnbIcon,
          iconChecked:
            classes.AirBnbIconChecked,
          checked: classes.AirBnbChecked
        }}
      />
    }
    label="Show Map"
    labelPlacement="start"
  />
</FormGroup>;

This switch is on or off depending on the prop mapShowing. When it gets toggled, it calls the function toggleMapShowing. Fairly straightforward! Now, within my LocationsGrid component, I toggle the map like so:

{
  this.props.mapShowing && (
    <div className={classes.mapDiv}>
      <MapAndMarkers
        locations={locationsSlicedDownOnPage}
        hoveredCardId={this.state.hoveredCardId}
      />
    </div>
  );
}

The state variable mapShowing and the toggleMapShowing function live within App.js.

Getting the map to push the list over was achieved using flex-box (how did we go without it?!) and inline-block:

mapDiv: {
height: "100%",
width: "65%",
display: "inline-block",
position: "sticky",
transition: theme.transitions.create("width", {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen
}),
[theme.breakpoints.down("sm")]: {
display: "none"
}
},
listGridDiv: {
overflow: "auto",
height: "85vh",
[theme.breakpoints.down("sm")]: {
justifyContent: "center",
}
},
parentDiv: {
display: "flex",
justifyContent: "space-between",
height: "100%",
overflow: "hidden"
},

This allows the map to kindly push its way onto the scene, and the flexbox grid of cards responds accordingly. The last thing I’ll point out here is that the cards are flex-start aligned when the map is in and centered when the map is hidden. This makes for a more attractive ui and is achieved with this simple ternary on the parent <Grid>:

justify={this.props.mapShowing ? "flex-start" : "space-evenly"}

I didn’t do it here, but the next step would be to mimic the ✓ vs. X in the AirBnb toggle switch:

I’m fairly confident a bit of digging into the various props of the material-ui Switch component would allow for this.

This tutorial will be continued in the next section, where we will cover building:

  • Working Pagination to make exploring the data easier/faster
  • A popup year filter that allows users to show NYT data by year
  • Text/Search Filtering to allow for string queries of the data
  • A responsive menu
  • General responsible responsiveness to make this app mobile-friendly

Note: This open source map got put into action for this Oaxaca Hiking Map Website. It has also been favorited over ten times on Github.

About the Author:

AirNYT: React-Virtualized + Material-UI Cards for Fast Lists

November 2nd, 2018

This tutorial will cover how to use React-virtualized with Material-ui Cards and Grid to make a list of image-heavy cards that loads extremely fast. Doing this not only allows for much faster loading and re-rendering (such as when using client-side filters) but also better user experience in general. This tutorial is part of a broader series on building an AirBnb-like interface for exploring New York Times travel recommendations.

We start with this app as our baseline:

Github: https://github.com/kpennell/nytairbnbbucketlist

Demo: http://nytrecsalaairbnb.surge.sh/

The Problem: Hundreds of Image-heavy Cards

This app is loading 400+ image-heavy cards. For fast wifi, this is generally fine. But for slower connections (and/or mobile), this app is going to feel sluggish. If I add client side filters, it will feel even more sluggish. And if someone were to use this for an app with 40000 instead of 400 cards, it would feel extremely sluggish. No one likes that.

Here are some snapshots of from the Chrome console before I ‘fix’ this problem:

The Solution: React-Virtualized

React-Virtualized is an awesome library written and maintained by Brian Vaughn (he works on the React team at Facebook). Brian describes React-Virtualized as a set of components for efficiently rendering large lists and tabular data. He gives a great explanation of the library and why he invented it here:

It is a great talk and the key element is this part about windowing: (https://youtu.be/t4tuhg7b50I?t=670):

Windowing is a technique of only rendering what a user actually sees in their browser. In other words, there’s no need to attach a bunch of list, table, grid items to the DOM that the user is not currently using or seeing. So the problem with my list of cards (in the example app, above) is exactly this: the user’s browser is forced to load a bunch of images that the user might not actually see or be using. Let’s fix this with React-Virtualized.

Implementing React-Virtualized

The current implementation of my Grid of Cards is fairly straightforward:

// LocationsGrid.js

class LocationsGrid extends React.Component {
  render() {
    const { locations, classes } = this.props;

    return (
      <div className={classes.root}>
        <Grid container justify="flex-start" spacing={16}>
          {locations.map((location, index) => (
            <Grid key={index} item>
              <LocationCard location={location} />
            </Grid>
          ))}
        </Grid>
      </div>
    );
  }
}

This maps over the props.locations and renders cards in a nice flex-box grid. Here’s the steps I’ll take to implement this same ui using react-virtualized.

First things first:

yarn add react-virtualized

Next, I’m going to use React-Virtualized AutoSizer and List components for this grid ui. Autosizer is a “High-order component that automatically adjusts the width and height of a single child”. Put a bit more simply, Autosizer is a component that goes around (as a parent or HOC) a List or Table component to allow it access to the width and height props. These width and height props are useful for making responsive or dynamic lists or tables.

The next component I will use is the List component. The List component is fairly self-explanatory in that it is what React-virtualized uses for ‘windowed’ or ‘virtualized’ lists.

Source: https://bvaughn.github.io/react-virtualized/#/components/List

Here is some code with inlined comments that show how I use AutoSizer and List together to implement my same Card grid.

<div style={{ marginTop: "10px", height: "80vh" }}>
  <AutoSizer>
    // The Autosizer component goes around the List component and you can see
    here the height // and width props that it will pass to List
    {({ height, width }) => {
      const itemsPerRow = Math.floor(width / CARD_WIDTH) || 1; // A calculation to establish how many cards will go on each row.

      // The || 1 part is a simple hack that makes it work in a really small viewport (if someone totally collapses the window)

      const rowCount = Math.ceil(locations.length / itemsPerRow); // List will need the number of rows in order to be able to properly know what to render and what not to

      return (
        <div>
          <List
            width={width}
            height={height}
            rowCount={rowCount}
            rowHeight={CARD_WIDTH}
            // CARD_WIDTH is a constant of 340

            rowRenderer={({ index, key, style }) => {
              // This is where stuff gets interesting/confusing

              // We are going to constantly update an array of items that our rowRenderer will render

              const items = [];

              // This array will have a start and an end.

              // The start is the top of the window

              // The end is the bottom of the window

              // the for loop below will constantly be updated as the the user scrolls down

              const fromIndex = index * itemsPerRow;

              const toIndex = Math.min(
                fromIndex + itemsPerRow,
                locations.length
              );

              for (let i = fromIndex; i < toIndex; i++) {
                let location = locations[i];

                items.push(
                  <div className={classes.Item} key={i}>
                    <LocationCard location={location} />
                  </div>

                  // Each of these items has the LocationCard in them
                );
              }

              return (
                // They get rendered into the Row

                <div className={classes.Row} key={key} style={style}>
                  {items}
                </div>
              );
            }}
          />
        </div>
      );
    }}
  </AutoSizer>
</div>;

If you happened to get lost in those comments and lines of code, let me try to simplify this:

We have an <AutoSizer> component. In our example, it calculates the (potentially) changing height and width of the user’s browser window.

Ok, then we have a <List> component. It will create our list. But we need to give it props first. If you check the docs for this component, you’ll see that it needs rowCount, height, rowHeight, rowRenderer, and width. rowRenderer (docs here) is the potentially confusing one. This is the function in charge of ‘creating’ or rendering our rows. But it needs to know which rows to render when. In this example, we give it a key and an index. The index tells the rowRenderer where exactly it is in the collection (be it row 2 or row 1,000,002).

From the docs:

index, // Index of row
key, // Unique key within array of rendered rows

Alrighty, so then we have that for loop in there:

for (let i = fromIndex; i < toIndex; i++) {
  let location = locations[i];

  items.push(
    <div className={classes.Item} key={i}>
      <LocationCard location={location} />
    </div>
  );
}

This for loop is creating a smaller array (from the whole big props.locations array) to be rendered within the window. If you’re still not quite getting it, I recommend logging index and items and then scrolling down, like so:

console.log("index " + index);

const toIndex = Math.min(
  fromIndex + itemsPerRow,

  locations.length
);

for (let i = fromIndex; i < toIndex; i++) {
  let location = locations[i];

  items.push(
    <div className={classes.Item} key={i}>
      <LocationCard location={location} />
    </div>
  );
}

console.log("items " + items);

And you should see something like this in the console:

What Did We Win?

What did we achieve with this slightly-confusing code? Let’s check the chrome console again:

The previous implementation had 329 requests and 29MB transferred, which took 8.46s to load:

The React-Virtualized example had 43 requests which transferred 3.6MB and loaded in 3.79s.

Using React-Virtualized allowed us to save a ton of bandwidth and user waiting time. Now if we could just get Soundcloud to do the same!

I hope this helped you understand the key points of using this incredible library. Upcoming tuts will get us back on track to finish up making this AirBnb clone.

Update: Brian Vaughn (the creator of React-Virtualized) submitted a pull request and showed how to do this tutorial using React-Window (a faster version of React-Virtualized): https://github.com/kpennell/nytairbnbbucketlist/commit/101a32bb0555f3a7cc29151de195882b249972e8

That said, here is the code for this tutorial using React- Virtualized: https://github.com/kpennell/nytairbnbwithvirtualized