Category Archives: Web Development/UX Design

Learning Guides, Web Development/UX Design

How to use GatsbyJS to build a blazing fast Drupal website

This is a guest post from Sujit Kumar. If you want to contribute guest posts to code(love), email [email protected]

What is Gatsby?

Gatsby is a static site generator that uses popular technologies such as ReactJS, Javascript and GraphQL in a way that is not dependent on external resources. This makes websites DDOS-resistant, faster, and more secure — and it is really easy to integrate with common content management systems like Drupal.

Why use Gatsby?

  • Unlike dynamic sites which render the pages on demand, static site generators pre-generate all the pages of the website.
  • No more live database querying and no more running through the template engine each time you load a page.
  • Performance goes up and maintenance cost goes down.
  • Using Gatsby means you can host the CMS in-house and publish the content generated by Gatsby as a static website.

It’s always good to increase the performance of Angular and React applications. This is one way you can do it.

GatsbyJS covers all the buzzwords out there like ReactJS, GraphQL, WebPack etc, but the coolest part is that you’re up and running in no time!

Since Gatsby is built on React you straight away get all the things we love about React, like composability, one-way binding, reusability and a great environment.

Gatsby makes Drupal work as a backend which means that we can get a modern stack frontend and complete static site with Drupal as a powerful backend.

Set up Drupal

  • You have to install and configure the JSON API module for Drupal 8.
  • Assuming you already have a Drupal 8 site running, download and install the JSON API module.
  • Composer require drupal/JSON API
    drupal module: install JSON. Or install it manually on Drupal 8 sites.
  • Next, we must ensure that only read permission is granted to anonymous users on the API. To do this, go to the permissions page and check the “Anonymous users” checkbox next to the “Access JSON API resource list” permission. If you skip this step, you’ll get an endless stream of 406 error codes.

After this, you should be all set. Try visiting http://yoursite.com/jsonapi and you should see a list of links.

Install gatsby

Now we need to work on Gatsby. The first thing we need to do is install the Gatsby client. If you don’t have it installed already, run this through NPM to grab it:

npm install --global gatsby-cli

That’ll give you the “Gatsby” cli tool, which you can then use to create a new project, like so:

 gatsby new my-gatsbyjs-app

That command basically just clones the default Gatsby starter repository and then installs its dependencies inside it. Note that you can include another parameter on that command which tells Gatsby that you want to use one of the starter repositories, but to keep things simple we’ll stick with the default. Now if we look at the project we can see a few different directories.

ls -la my-gatsbyjs-app/src/
#> /components
#> /layouts
#> /pages

Pages

The pages directory contains the pages. Each file becomes one page and the name is based on the file name. Each of these files contains a react component.

This is the index.js that we just created.

<script src="https://gist.github.com/nehajmani6/d0509a7b7bf0d8c2e7cf2e4634812155.js"></script>

Layouts

The Layout directory contains a layout that wraps our pages. These layouts are higher order react components that allow defining common layouts and how they should wrap the page. We can place our page where ever we want within the layout using the prop children.

Let’s look at a simple layout component

 <script src="https://gist.github.com/nehajmani6/2e23c6ce6f152dfe5619c4c17394efaf.js"></script>

As you can see, our layout component takes two props.

One is children prop, where the page is wrapped by us.

The second prop is the data. This is actually the data we fetch with the GraphQl query that is at the end of the code snippet – which in this example fetches the title from the gatsby-config. 

Components

The last directory is the components. It is used for creating general components. Fire up the newly generated site.

To run the development mode of the site and to get a Rough idea, run the command:

gatsby develop  
#> DONE Compiled successfully

We’re now up and running! See for yourself at http://localhost:8000

Once complete, you have the basis for a working Gatsby site. But that’s not good enough for us! We need to tell Gatsby about Drupal first.

For this part, we’ll be using the gatsby-source-drupal plugin for Gatsby. First, we need to install it:

cd my-gatsbyjs-app
npm install --save gatsby-source-drupal

Once that’s done, we just need to add a tiny bit of configuration for it, so that Gatsby knows the URL of our Drupal site. To do this, edit the gatsby-config.js file and add this little snippet to the “plugins” section:

plugins:


[
 {
   resolve:`gatsby-source-drupal`,
   options: {
     baseUrl: `http://yoursite.com`, //Drupal site url.
apiBase: `jsonapi`, //This the jsonapi endpoint
   },
 },
]

You’re all set. That’s all the setup that’s needed, and now we’re ready to run Gatsby and have it consume Drupal data.

Run gatsby

Let’s start the development environment to see the Gatsby running.

Run this to get Gatsby running:

gatsby develop

If all goes well, you should see some output with gatsby default starter:

You can now view gatsby-starter-default in the browser.

http://localhost:8000/

View GraphiQL, an in-browser IDE, to explore your site’s data and schema

http://localhost:8000/___graphql

Note that the development build is not optimized.
To create a production build, use gatsby build

(If you see an error message instead, there’s a good chance your Drupal site isn’t set up correctly and is erroring. Try manually running “curl yoursite.com/jsonapi” in that case to see if Drupal is throwing an error when Gatsby tries to query it.)

You can load http://localhost:8000/ but you won’t see anything particularly interesting yet. It’ll just be a default Gatsby starter page. It’s more interesting to visit the GraphQL browser and start querying Drupal data, so let’s do that.

Fetching data from Drupal with graphql

Load up http://localhost:8000/graphql in a browser and you should see a GraphQL UI called GraphiQL (pronounced “graphical”) with cool stuff like auto complete of field names and a schema explorer.

Clear everything that is on the left side and start inserting the open curly bracket and it will auto insert the closing curly bracket. Then click ctrl + space to view the auto-complete, which will list the all possible entity types and bundles that we can query.

It should look something like this:

GatsbyJS

For example, if you want to query Event nodes, you’ll enter “allNodeEvent” there, and drill down into that object.

Here’s an example which grabs the fields (field_task_name, field_date and nid) of the TodoList nodes on your Drupal site:


{
   allNodeTodoList{
       edges{
           node{
               nid
               field_task_name
               field_date
           }
       }
   }
}

Note that “edges” and “node” are concepts from Relay, the GraphQL library that Gatsby uses under the hood. If you think of your data like a graph of dots with connections between them, then the dots in the graph are called “nodes” and the lines connecting them are called “edges.”

Once you have that snippet written, press “control+Enter” to run it, and you should see a result like this on the right side:


{
 "data": {
   "allNodeTodoList": {
     "edges": [
       {
         "node": {
           "nid": 1,
           "field_task_name": "Learn Drupal",
           "field_date": "2018-12-14"
         }
       },
       {
         "node": {
           "nid": 2,
           "field_task_name": "Complete drupal task",
           "field_date": "2018-12-15"
         }
       },
       {
         "node": {
           "nid": 3,
           "field_task_name": "Learn gatsby",
           "field_date": "2018-12-16"
         }
       },
       {
         "node": {
           "nid": 4,
           "field_task_name": "Gatsby Project",
           "field_date": "2019-01-10"
         }
       }
     ]
   }
 }
}

Note the same code will give the data from Drupal which includes the reference data, URIs etc.

Pretty cool right? Everything you need from Drupal, in one GraphQL query.

So now we have Gatsby and Drupal all setup and we know how to grab data from Drupal, but we haven’t actually changed anything on the Gatsby site yet. Let’s change that.

Displaying drupal data on the Gatsby site

The cool thing about Gatsby is that GraphQL is so baked in that it assumes that you’ll be writing GraphQL queries directly into the pages or the components.

In your codebase, check out src/pages/displaynodes.js.

<script src="https://gist.github.com/sourabhsp21/1f69d5cffc5a4bd220b243a2dd8fb3a5.js"></script>

(Note, this assumes you have a node type named “Page”).

All we’re doing here is grabbing the node (task name and task date) via the GraphQL query at the bottom, and then displaying them in a table format.

Here’s how that looks on the frontend:

GatsbyJS

And that’s it! We are displaying Drupal data on our Gatsby site!

Author Bio:

Sujit Kumar is VP of Strategy & Marketing at Valuebound taking care of all aspects of lead generation, company and brand promotion and sales activity. He brings nearly 14+ years of marketing experience, strategic thinking, creativity, and operational effectiveness. Prior to joining Valuebound, Sujit worked in marketing management positions with professional services firms.

Cryptocurrency/Blockchain, Data Science/Artificial Intelligence, Learning Guides, Web Development/UX Design

The Best Programming Language to Learn: a Definitive Guide.

Most people approach me often ask the same question: what’s the best programming language to learn? The answer is: it depends. I wrote an article that declared the mathematical and analytical skills behind programming are what really matter. Now, I’m a bit wiser –so I’ve had the time to break it down into a more tangible and useful answer.

What is the best programming language to learn? It depends, and you can be much more efficient with your time by knowing which programming language is the best for what you want.

So I’ve broken down the best programming language to learn for a variety of needs. I took into consideration the amount of time you need to invest in a programming language and the power you need for different tasks.

You want a versatile, general-purpose language that can be narrowed to different tasks without too much hassle.

The best programming language to learn, source: Pixabay

Python is a programming ecosystem with a vast array of communities and libraries for different use cases. From Django for web development to Pandas for data, Python is the Swiss-army knife of programming languages. Its syntax is also very approachable, and there are tons of tutorials and documentation for beginners. These libraries tend to be almost like learning a new syntax or paradigm.

Still, the ability to import libraries of different kinds and have a relatively consistent experience puts Python up here. If you want a simple intro-level programming language, Python is a great choice. With the second most active community on Github (at about slightly under 15% of all active users), you’re sure to find many projects and usable components to play with in Python.

Python Resources:

Learn Python

This step-by-step tutorial teaches Python in an accessible manner. It makes it easy for you to go through the basics of everything from data structures to how to structure functions. That makes it ideal for people who don’t have programming experience.

11 Beginner Tips for Learning Python

This set of tips is a handy primer for not only learning Python, but really a generalizable way to learn and practice all kinds of different programming languages.

Zen of Python

The Zen of Python is more philosophical than practical. Still, it serves as a useful reminder of the ideals of Python programming and the ideals one should strive for. Simple, after all, is better than complex.

Codecademy: Learn Python for Free

This free interactive Codecademy course is a great way to start with Python basics and syntax. Use it to cement the theory you’ve learned and start practicing with Python.

Web Development Using Python and Django

Python is versatile mostly because there are tons of documentation and frameworks. Django is a content management system built on Python. This curated curriculum will help you learn what you need to build fully-fledged websites with Python by tapping into Django.

You’re interested in working with data, in a data analysis or data science capacity or as a data engineer/machine learning engineer

The best programming language to learn, source: Pixabay

When it comes to the data ecosystem, you’ll want to learn SQL as a domain-specific way to work with data. However, SQL is not a general purpose programming language, but merely a utility to deal with one data type over another. You can think of it as a complex interface to the .sql data format.

There are two obvious choices here, R or Python. Academics tend to use R. It used to have the bulk of good data visualization and analytics libraries. Now, however, the open-source Python community has sprinted to catch up. With the advent of machine learning, the balance has shifted towards Python.

Previously, I wrote about both R vs. Python a few years ago. I came out with the conclusion that both had their uses. It was perhaps best to learn both. Practically speaking however, if you’re dealing with large amounts of data ,Python gets the slightest of edges here as the best programming language to learn for data purposes, especially if you’re coming from a programming background in the first place — it’ll be easier for you to work with Python’s syntax than R.

Python and Data Resources:

Data Science Sexiness, R vs Python

I wrote this guide describing the differences between R and Python, and listed a bunch of learning resources for both. I concluded it might be best to learn both, but I’ve since become immersed in the Python ecosystem when it comes to data.

Introduction to the Machine Learning Stack

I wrote this tutorial which summarized the frameworks and libraries you need to know to get started doing machine learning with different frameworks, most of which have Python ports or APIs so you can write code in Python (or in any case, Pythonic syntax) and get started.

Pandas Cookbook

Pandas was where I really started practicing programming: wrangling datasets is a passion of mine. This tutorial walks through how to use Pandas with an example dataset. You’ll learn how to import data of different formats, transform it in different ways, and then extract and export it.

How to do Common Excel and SQL Tasks in Python

Another tutorial I wrote helps you port some of the logic and functions in both Excel and SQL to Python. Do everything from importing data to analyzing it in the summary form or filtered form you’ve come to expect.

Machine Learning in Python

This curated curriculum takes your Python skills and helps you learn machine learning theory. By pairing the two, you can start working on machine learning projects by the end.

You want to build mobile applications that require access to native functionalities such as a phone camera

The best programming language to learn, source: Pixabay

Depending on what ecosystem you want to build in, the best language is quite selective. If it’s the Android ecosystem, you’re going to have to learn Java.

Meanwhile, if you’re interested in building for the iOS ecosystem and getting placed on Apple’s App Store, you’ll have to learn Swift. Swift is Apple’s official programming language for its laptops based on MacOS, iOS, or for Apple Watch apps.

There are other ecosystems such as Microsoft, which needs C#. There are also cross-platform programming languages such as React Native. Microsoft doesn’t have as much market share as either Android phones or iPhones. Reach Native doesn’t have access to as many of the specific native functions on either device (and you’ll have to compile down to Swift or Java to get those features). Still, they’re handy languages to know about, even if they might not be the best — unless you were trying to launch on as many platforms as possible.

Resources:

Android Application Development

Learn the ins and outs of Android application development, from building an application to how debug common issues.

Introduction to Swift

This interactive set of courses will help you get through the basics of Swift and building iOS applications. You’ll pass to an intermediate stage/course once done.

400+ Swift Language Video Tutorials

If video learning is more of your thing, look no further than this series of video tutorials on Swift topics. They’re broken down into sets of continuous playlists, so you can pick and choose a particular curated playlist or choose a particular topic to focus on.

React Native Tutorial

This React Native tutorial and documentation from Facebook is a fairly comprehensive overlook on how the versatile cross-platform framework works.

Expo

If you want to speed up your app development cycle across multiple platforms and want to stick to using JavaScript for your mobile app coding, Expo can be a quick, iterable solution.

You want to build the latest web applications

The best programming language to learn, source: Pixabay

For web development, PHP used to be the default, powering everything from e-commerce sites to WordPress itself. Now though, most people have shifted to JavaScript and different frameworks within it. There’s a bit of a fight going on between the major tech companies on building web development interfaces, with Google sponsoring Angular.js while Facebook builds React.js. In practice, these mega-corporations are building the most recent web development frameworks for their needs and then open-sourcing and supporting the developments.

Both are doing it on JavaScript, so if you want to build the latest and greatest in web applications and benefitting from their work and others, look no further. JavaScript is the best programming language to learn for cutting-edge web development applications. It boasts the most active community on Github with over 22% of all active users participating in the JavaScript community.

JavaScript Resources:

An Introduction to JavaScript

This wiki gives you a broad overview of JavaScript and how it serves web content. You’ll understand basic concepts like how JavaScript interacts with browsers once you’re done. You can then take the next step towards learning more powerful frameworks.

jQuery Intro

jQuery is a powerful JavaScript library that allows you to do powerful things such as animations with a one-word function. Use this tutorial to grasp the basics and combine it with HTML and CSS to serve dynamic web content easily.

How to Learn React — A roadmap from beginner to advanced

This roadmap will help you conceptualize your roadmap for learning JavaScript frameworks like React.js.

React.js, Codecademy

React.js is a powerful framework to create web interfaces. Practice with this Codecademy course.

MEAN Stack Tutorial

This tutorial will summarize all of your theory-based learning towards building a MEAN stack application that will serve as a Reddit clone. This is a full-featured web app that has user authentication, databases through MongoDB, routing and linking through Express and a back-end server through Node.js and a combination of Angular (though React can also be used in this situation). At the end of this tutorial, you should be able to extend your learnings and build full-fledged web apps.

You need to do something that requires very high performance (ex: cryptography)

The best programming language to learn, source: Pixabay

For tasks that require a lot of compute power and manipulation of lower-level processes such as dynamic memory allocation, it’s best to work in C++. Lower-level tasks require more efficient implementations of memory and space and involve working closer to hardware in order to get higher performance. C++ is lower-level than all of the languages discussed about yet is also still readable and compilable enough so that with some practice, you can be conversant in it.

Python can access lower-level functions with something called Cython using the C programming language. Bitcoin is coded in C++, including its advanced cryptographic features. In order to do something at a highly performant level, you’ll likely need to access C++ and its superior lower-level flexibility.

C++ Resources:

Introduction to C++

This edX course, provided by Microsoft, will help you get started with C++ and its basics.

C++ Language

This wiki helps you tackle C++ from A to Z. There’s different sections dedicated to everything from how to write functions in the language to how to deal with different variables and types.

C++ Codecademy

Consolidate all of the theory you’ve learned by practicing with this free C++ course with Codecademy.

Cython Tutorial

Cython allows you to access C++ functions while using Python, combining the versatility of the Python ecosystem with the power of C++.

C++ Cryptography Libraries

If you want to look into advanced functions such as cryptography, look through this list of C++ cryptography libraries to get you started.

—–

I hope this tutorial has helped you determine what the best programming language to learn for you. If you have any questions, feel free to ask me at [email protected]. Please leave a comment below if you want to give feedback or if you think I’m missing something 🙂