React Js2

React JS And GraphQL

Abstract

This article is focused for new react developers who want to experiment with different data libraries and want to use react as prop driven framework. React itself is a view library and can be greatly enhanced using a prop driven approach to components.

Introduction

What is React JS ?

React Js is a view library developed by Facebook, specifically used for creating interactive user interfaces for single page applications. React.js basically allows to create reusable UI components.
Purpose of using react is to develop fast, scalable and simple components in UI.

Basic Features Of React JS

JSX

Using JSX adds XML type syntax to JavaScript, basically JSX extends JavaScript so that HTML/XML like structures can be used with JavaScript. As mentioned JSX is an extension for JavaScript therefore browsers have hard time understanding it unless it is compiled into plain JavaScript. Hence it is required to use JSX compilers. One the most commonly used such compiler is Babel.
For instance a JSX component looks like this

const exampleComponent = <span className = “title”> Hello World </span>

Unidirectional data flow

React follows a top to down flow of data i.e data is passed down to the components from parents components to child components with the help of props. Any property passed down by a parent component to a child component is called a prop. Besides props, as data in each component can maintain their own States and this plays a major part in component re-rendering.
dataflow

Virtual Document Object Model

In order to make updates to the page React creates an in-memory data structure cache, which computes the changes. This enables the developer to write code to handle such scenario, if the whole page is updating where in React only renders the component in question.

That is all we need to know about React for this user guide. Next we are going to get an overview of Graph QL

What is GraphQL

I am not going to discuss much about GraphQL in this article but just for understanding purposes. Basically GraphQL is a query language for your API based around the Graph algorithm. This is also developed by Facebook. GraphQL lets developers to define types of Data.

Writing Your First React And GraphQL Application

To keep this article short and concise, we are going to use Facebook create-react-app incubator.

Why create-react-app

  • Easy To Use
  • Well Documented
  • Already has all the Dev dependencies in place
  • Production ready
  • An active repository

In order to use GraphQL, we are going to mock a GraphQL server. Though, one can find many GraphQL mocks on Git Hub, we are going to use “json-graphql-server” in this article. It is easy to use without getting into the tedious job of setting up an API server and connecting it with GraphQL to justify purpose of this article.

Setting Up a GraphQL Server

First of all create a folder for your GraphQL server MyMockGraphqlServer. Once created then navigate into the folder and open the terminal. Then, type in “npm install -g json-graphql-server” command. After this, we need to create db.json file that will serve as a data store for the GraphQL server.

For the purpose of this tutorial we are going to create an app that lists down my favourite bands with some descriptions about the band.

First we need to add data to our db.js file

Db.js file

module.exports = {
bands: [
{ id: 1,
band: "Metallica",
yearsActive: "1981 - present",
members: ["James Hetfield", "Kirk Hammet", "Robert Trujillo", "Lars Ulrich"],
website: "www.metallica.com",
imgURL: "https://i.imgur.com/rc6tJRo.png"
},
{ id: 2,
band: "Pink Floyd",
yearsActive: "1965 - 1995",
members: ["Nick Mason", "Roger Waters", "Richard Wright", "Syd Barret", "David Gilmour"],
website: "www.pinkfloyd.com",
imgURL: "https://i.imgur.com/axI66xc.jpg"
},
{ id: 3,
band: "Rammstein",
yearsActive: "1994 - present",
members: ["Richard Z. Kruspe", "Paul H. Landers", "Till Lindemann", "Christian Flake Lorenz", "Oliver Ollie Riedel", "Christoph Doom Schneider"],
website: "https://www.rammstein.de",
imgURL: "https://i.imgur.com/bpCHwm4.jpg"
},
{ id: 4,
band: "Led Zeppelin",
yearsActive: "1968 - 1980",
members: ["Jimmy Page", "Robert Plant", "John Paul Jones", "Jon Bonham"],
website: "www.ledzeppelin.com",
imgURL: "https://i.imgur.com/xS4Xua3.jpg"
}
]
}

Once done save your db.js file, then open up the terminal and type in “json-graphql-server db.js –p 3001” command
Hit enter, this should run your GraphQL server for the given data.

Now open browser and enter the url “localhost:3000” and hit enter. This should open up the following screen for you.
React & graphql1

Now if you press the play button you should see results from your db.js file.
React & graphql2

We have successfully created a GraphQL server that serves a list of my favourite bands. All that left now is to connect this server to our react app.

Create React App

In order to speed up the setup process we are going to use Facebook “create-react-app” module as its fast, efficient and production ready. You can read more about create-react-app at https://github.com/facebook/create-react-app
Open up the terminal and type in “npm install -g create-react-app” command and hit enter. This should install create-react-app module globally.
Now create your project folder and run command from terminal by typing “create-react-app
This should install required dependencies and you should have a ready to run project at your hand. Navigate into the project folder and open the terminal. Then, execute “npm start” and this will run your app on localhost:3000. Now if you visit the URL, you should be able to see this page
React & graphql3

And your project structure should look something like this
React & graphql4

We are going to do most of our stuff inside src folder.

Connecting your app to your GraphQL server
Open up the index.js file and code in the following

index.js file

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ApolloClient from "apollo-boost";
import { ApolloProvider } from 'react-apollo'
import registerServiceWorker from './registerServiceWorker';

const client = new ApolloClient({
uri: “http://localhost:3000/”
});

ReactDOM.render(

, document.getElementById(‘root’));
registerServiceWorker();

Once done create-react-app has neat little feature that will automatically reload the page. If you open up the console and navigate to the react tab (Install react dev tools extension for your browser if you don’t see the react tab.) you should be able to see the ApolloProvider at top of your app.

React & graphql5

Now we need to write a query that would fetch data from GraphQL server. For this, we are going to create an app which is going to show a list of my favourite bands with band art , band name, members, years active and a link to visit the bands official website. Therefore, our query should look something like this :

React & graphql6

Open up your App.js and add the following imports
React & graphql7

Article Component

We need an article component which will be responsible for rendering each band with description. This article component needs following props in order to full fill our requirement “name, members, description, yearsActive, imgURL
We will write an Article function that will receive props as parameters and return an article component. The article component should look like this
React & graphql8

App Component

Now for our App component, we are going to add the above written Graphql query inside app.js file and we can use the “graphql” import from “react-apollo” to wrap our App component with the query. The export line would look something like this

React & graphql9

Now if we go to our browser and look at react tab under the dev tools again, we should be able to see the updates what we made to the code. Basically, the graphql import fetches data from the graphql server and injects them as props to our App component. We should be able to see a data prop in our App component, which will contain data from our server as well as some of the other props. That, we can use to run our app smoothly.

React & graphql10

We can see a query component at the top of our App that will inject the props to our components, and we can see “allBands” props under the data prop. This is basically the result from allBands query. Besides the actual data, data prop also consists various useful props such as loading and variables props. The loading prop tells us whether the query is finished loading. We can use this to write defensive code and only load the app, once query is finished. Variables prop stores that if any variables are passed to the query.
Now all that is left is to modify our App component in such a way to render each article, when received from the server.

First we need to add some basic css to our App.css file. Open up the App.css and type in the following CSS

App.css file

body {
background-color: #f2f6f6;
font-family: Helvetica;
margin: 0;
padding: 0;
line-height: 1.35em;
}

.container {
max-width: 1190px;
padding: 15px;
margin: auto;
}

section {
padding: 15px;
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
}

article {
position: relative;
margin-bottom: 30px;
background-color: white;
margin-left: 15px;
margin-right: 15px;
filter: drop-shadow(5px 5px 3px rgba(0, 0, 0, 0.09));
padding-bottom: 55px;
}

article:hover {
filter: drop-shadow(10px 10px 4px rgba(0, 0, 0, 0.05));
transform: scale(1.02);
transition: 0.15s ease-in;
}

article img {
width: 100%;
height: 315px;
}

h1,
p,
a {
margin: 15px 15px;
}

a {
display: inline-block;
background-color: green;
padding: 10px;
color: white;
text-decoration: none;
border-radius: 4px;
position: absolute;
overflow: hidden;
bottom: 0;
}

a:hover {
background-color: yellowgreen;
transition: 0.25s ease-in;
}

@media all and (min-width: 20em) {
.container {
width: 100%;
padding: 0px;
margin: auto;
}

article {
flex: 0 1 calc(100% – 30px);
}
}

@media all and (min-width: 40em) {
article {
flex: 0 1 calc(33% – 30px);
}
}
@media all and (min-width: 60em) {
article {
flex: 0 1 calc(25% – 30px);
}
}

Once done move to the App.js file and modify your app component , it should look something like
React & graphql11

We check if the data loading prop is done and then we run a map function on the allBands data, which returns Article component written above. Finally when you save your app.js file and open up the browser you should be able to view the changes you have made in real time.
React & graphql12

Viola you have successfully created your first “React App With GraphQL

 

About Author:

Nadeem Khan is a Full stack developer currently working with QSS Technosoft as a Team Lead. His drive in life is to learn new things, be it technology related to improve technical stack or picking up new hobbies mostly video games :) . He wants to do it all. He has worked in React, MongoDb, Graphql ,SQL, API.AI, Interactive chat bot creation, Node.JS, Express.js, Strongloop, A bit of React Native, Android (“Experimental Projects :)”). He quoted as saying " I am always motivated by the why and how of things."

About QSS:

QSS has a proven track executing React JS with GraphQL applications for its esteemed customers. The company has a core competency in developing and delivering Enterprise level React JS with GraphQL applications. The React JS with GraphQLcompetency has experienced and dedicated team of React JS with GraphQL developers. To Know More...