Jan 07 2020
Jan 07

We’ve already discussed in our previous blog, how Progressive Web Apps (PWAs) are trending and making web apps load faster, ensuring exceptional user experience.

For one of our clients, we implemented this solution to create a budget planner and currency calculator for a giant travel retail outlet and helped boost the sales just after 3 months of its deployment. 

Let’s dig deeper into the technical details and understand the nitty-gritty of creating PWA using React on a Drupal 8 website. 

Why Opt For This Approach

With the increasing popularity of ReactJS, JavaScript libraries and frameworks prove to be useful in building complex applications by seamlessly getting embedded on a Drupal site, thus combining the robustness of an API-first CMS with slick and quick React frontend to collectively give way to amazing digital experiences along with future-proof builds. 

To create PWA on a Drupal site, one can use Service Workers, Web App Manifest and HTTPS. However, opting this approach will not unnecessarily increase the load of the application and will reduce the entire application load time. Possessing knowledge of React in addition to Drupal is the only requisite here to implement the approach.

How To Create PWA With React on Drupal 

Step 1: Create React Environment

In our last blog on React, we learned how to set up Setup React App From Square One Without Using Create-React-App  Once the environment is set up, we shall move forward to creating a React app.

Step 2: Create React Application

Before looking into the process of creating a React application, let’s get a hold of the below terms:

  • Components - It's the building block of any react app. Basically, there are two types of components.
    • Functional
    • Class (From 16+ react version, this component is deprecated. Only functional components are used.)
  • Props - Arguments passed in react components to send data to components. 
  • States - Behaves like a data store to components. It’s mostly to update components when user performs some operation like clicking buttons, typing some text etc.

Now, let's write our first code block of React by using ES6 classes to create a React component called App.

index.html

class App extends React.Component {

  //...}

Now we'll add the render() method to render DOM nodes.

index.html

class App extends React.Component {

  render() {

      return (

          //...

      );

  }

}

In return, we’ll insert a simple HTML element. 

index.html

class App extends React.Component {

  render() {

    return <h1>Hello world!</h1>

  }

}

Finally, we're going to use the React DOM render() method to render the App class we created into the root div in our HTML.

index.html

ReactDOM.render(<App />, document.getElementById('root'))

Here is the full code for our index.html:

index.html

<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8" />

 

    <title>Hello React!</title>

 

    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>

    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>

  </head>

 

  <body>

    <div id="root"></div>

 

    <script type="text/babel">

      class App extends React.Component {

        render() {

          return <h1>Hello world!</h1>

        }

      }

      ReactDOM.render(<App />, document.getElementById('root'))

    </script>

  </body>

</html>

Now if you view your index.html in the browser, you'll see the h1 tag we created rendered to the DOM.

hello world screenshot

Hello World screenshot

Step 3: Visualizing the React component in Storybook

Storybook is a user interface development environment and playground for UI components. 

Visualizing the React component in Storybook

The tool allows testing the components independently and interactively in an isolated development environment. Story file code looks like:

Story file code

After running `npm run storybook` command, storybook will open on localhost server as shown in the attached screenshot.

storybook screenshot

 

Step 4: Creating Custom Block API in Drupal 8 and Embedding React application 

On running npm run build command on React application, it creates this react minified JS file:

/drupal_root/module/custom/react_block/react_block.libraries.yml

jsfile

The minified js file searches for the markup in the /drupal_root/module/custom/react_block/src/Plugin/Block/ReactApp.php file

and on finding the div ID, it renders itself at that point.

file getting rendered

And this is how the React block renders itself on our Drupal 8 website and makes the website a PWA.

Srijan can help you leverage the power of React with API-first Drupal to create robust content workflows and hence lead to joyful editorial experiences for your business to evolve. Get in touch with our experts or leave your queries in the comment section below and let’s get the conversation started.

Nov 01 2019
Nov 01

The breakthrough in technology has brought a whole new range of tool suite for developers to make the software development process more efficient. React App is among one of them! A prominent tool recommended by the React community to create single-page applications (SPAs) and also get familiar with React.

React App ensures that the development process is refined enough to let developers leverage the latest JavaScript functionalities for better experiences and optimization of the apps for production.

For one of our clients- a giant retail travel outlet - who went out to get a realistic travel budget in mind for the travelers to plan ahead and avoid spending shocks along the way we built a budget planner. 

Built on React.js on top of Drupal, it is a dynamic feature and can be added anywhere in the website (under blogs, services) without coding. 

Creating React App doesn't require configuration of web pack (bundler for modules) and babel (compiler). They come inbuilt. Developers can right away start with coding here. However, the drawback is that they won’t be able to get an idea about things happening in the background.

If we set up React App without using the Create React App, then we will be able to know which all NPM packages/components are needed to make react app working.

About React App

Create React App was built by Joe Haddad and Dan Abramov. The GitHub repository is well-maintained by the creators to fix errors and deliver updates frequently. 

It is a prominent toolchain for building apps quickly and efficiently. A toolchain can be defined as a set of different s/w development tools that are optimized to perform specific functions. For example, the C++ development process requires the compiler to compile the code and a build system, say CMake, to manage all the dependencies. Similarly, the React App is used to create “hello-world” applications.

This blog will showcase how to create a React app from scratch. The prerequisite is to have the NPM package manager installed in the system.

Below mentioned are the steps for the same-

Step 1- Create an app directory

mkdir myApp

Step 2- Access myApp folder and run 

npm init

This, in turn, will create a package.json file for which you can provide the name and version.

Or

npm init -y

This will create a package.json file with a default package name and version.

Step 3- Install react and react-dom packages

npm install react react-dom

This will create a node_modules folder with all dependent libraries to further add dependency inside package.json file)

Step 4- Create a .gitignore file, to avoid pushing unnecessary files to GitHub

vi .gitignore

Under files section, add all the files which you don’t wish to be tracked by Git

  1. node_modules
  2. dist
  3. ._

dist ( Distributed folder ):- This is an auto-generated build directory. We don’t require this folder because it will be generated by the compiler.

Step 5- Create an app folder

mkdir app

Access app directory and then create three files 

  1. touch index
  2. js index.css
  3.  index.html

Step 6- Edit index.html and add below snippet

<!DOCTYPE html>

<html>

<head><title>

my-app

</title></head>

<body>

<div id="app"></div>

</body>

</html>

( No need to add any styling inside index.css file as of now )

Step 7- Edit index.js file and add below snippet

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

class App extends React. Component{

render(){

return(

<div>Hello World</div>

)

}

}

ReactDOM.render(<App />, document.getElementById('app'))

At the time of running this JSX code (XML/HTML- like syntax used by React that extends ECMAScript) in the browser, it will drop an error. Because the JSX code browser doesn’t understand and that is when we require Babel and Webpack.

npm install --save-dev @babel/core @babel/preset-env @babel/preset-react webpack webpack-cli webpack-dev-server babel-loader css-loader style-loader html-webpack-plugin

NPM install takes 3 exclusives, optional flags that either save or duplicate the package version in your main package.

1.  JSON: -S, ~save: 

The package appears in your dependencies

2. -D,~save.dev: 

The package appears in your devDependencies

3. -O, ~save-optional:

The package appears in your optionalDependencies

We will use Flag--save-dev to differentiate between built dependency & app dependency. 

Once installed successfully, you can check the package.json file to check the differences.

Webpack Configuration

Webpack, as stated is a module bundler, which primarily focuses on bundling JavaScript files for usage in a browser. Though it is also capable of transforming, bundling, or packaging just about any resource or asset.

Check the steps below for webpack configuration-

touch webpack.config.js

Step 1- Add below snippet in this file

var path = require('path');

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

entry : './app/index.js',

output : {

path : path.resolve(__dirname , 'dist'),

filename: 'index_bundle.js'

},

module : {

rules : [

{test : /\.(js)$/, use:'babel-loader'},

{test : /\.css$/, use:['style-loader', 'css-loader']}

]

},

mode:'development',

plugins : [

new HtmlWebpackPlugin ({

template : 'app/index.html'

})

]

}

Step 2- To allow babel-loader work well, we have to add babel preset config to package.json

"main": "index.js",

"babel":{

"presets" : [

"@babel/preset-env",

"@babel/preset-react"

]

}

Step 3- To run build, we need to add webpack to script within the package, i.e.,  package.json

"main": "index.js",

"babel":{

"presets" : [

"@babel/preset-env",

"@babel/preset-react"

]

},

"scripts": {

"create": "webpack"

},

Step 4- Run below command

npm run create

With this, webpack will be created, which, in turn, will create a dist folder and our bundle file including index.html.

Watch this video to learn more about it

[embedded content]

Step 5- Now to start webpack dev server, add below snippet inside package.json file

"scripts": {

"start": "webpack-dev-server --open"

}

It will start building our code as soon as we run npm start.

Step 6- All setup is done. Now run `npm run start` command to see the result on the browser.

The final directory structure will somewhat look like this as shown in the picture - 

Note: You might observe some storybook related extra files in the picture. However, these files won’t be visible in your setup. If you want to know about the storybook, stay tuned for our next blog.

Conclusion

I hope that now you have understood the fundamentals of Create React App better. If Yes, then implement the given steps right away and start building your awesome ideas!

Stay tuned for my next blog in which I will discuss Storybook. 

Happy Coding!

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web