Build a MERN Stack Application : Part 121 min read

0
829
Build a MERN Stack Application
12

Build a MERN Stack Application

Rise of Javascript and the bifurcation of Full-Stack Development into multiple specialized sub-domains like Front-End Development, Back-End Development and more, has heralded the Developers in a new era of Tech-Stack Development. And there have been good reasons for the same: While using Front-End Frameworks and Libraries would definitely simplify your task, there’s more to this than meets the eye. Developing Web Applications with Vanilla JS and simplistic HTML & CSS would require you to make extensive use of DOM to get JSON Data and append it to the HTML Elements.

This approach works while you are prototyping but later your JS and CSS would fatten up, bringing down the Performance, while making simple changes and bug fixes would require extensive development. Storing your Data in the DOM and making sense of the code would be too much of an issue.

Build a MERN Stack Application

Here comes in a Front-End Framework or Library: Breaking down your Code into Components will make them reusable and maintains your User-Interface. You can structure your Data Flow in the Application with them and use of Preprocessors and Transpilers easily.

It will also help you follow a Design Architecture that would help you while you are scaling. It brings the Speed and Maintenance in your Application.

In this Article Series, we will be covering on how you can develop a Full-Stack Application using MERN Stack and we will be covering all the basics of each of the technologies that will go in our efforts of developing and deploying a Full-Stack App.

What is MERN Stack?

MERN simply stands for : MongoDB, Express, React and Node which makes it a powerful combination for developing Full-Stack Applications with robust tools and technologies. MERN Stack allows the development process to be simplified by breaking down into multiple bits and create scalable applications that can be deployed with ease.

Build a MERN Stack Application
MERN Stack. Image Credits: CodingTheSmartWay.com

MERN allows Developers to follow up with a Model View and Controller (MVC) architecture thus making the development workflow smooth and comprehensible with a gentle learning curve.

React is a popular Front-End Library that has been developed by Facebook and has been in Open-Source for past few years. The advantages provided by React over other Front-End Frameworks and Libraries make it quite popular in the Javascript Fraternity along with a community of developers supporting it.

Some of the features like Virtual DOM and JSX (XML-Like Syntax which combines both HTML and Javascript) make it extremely modular and handy while developing Web Applications and even Mobile Applications (with React Native).

Build a MERN Stack Application

NodeJS is an efficient and lightweight runtime environment which is built on top of Chrome V8 Javascript Engine. Its support for an Event-Driven and Non-Blocking I/O Model makes it extremely modular for developing Server-Side Interface for Applications.

Express on the other hand is a framework that relies on NodeJS and abstracts most of the handlers for our requests that we make to the Server-Side Interface. MongoDB is a Relational Database Management System (RDBMS) which allows to index our Database Files and define Schemas that can be easily set up to store our data in a flexible and secure manner.

Build a MERN Stack Application
Developed with MERN Stack. Image Credits: DZone

What are we going to build?

In this Article Series, we are going to build a Full-Stack Blog Application using MERN Stack with some basic functionality and actually deploy it on Amazon Web Services (AWS) to be accessed by any User across the globe. Our Blog Application would support these basic features like checking out all the Blogs, Upvoting a particular Blog, Adding new Blogs and Comments, and more.

Build a MERN Stack Application

In Part 1 of the series, we will be covering on how we can develop a basic and intuitive User-Interface of our Blog Application using React via Create React App and explore some of the functionalities behind this. If you are new to React, you can check out our previous blog for the same, though things would be kept as simple as possible here.

What is React?

React is a Front-End Library developed by Facebook that relies on an all-new JSX Syntax for rendering Web Applications with reusable components. React is now considered to be one of the most influential Javascript Library (beside JQuery) to have put its mark on the Web Development Community. The advantages of React are huge: Virtual DOM, Stable Code, Proper Maintenance and powerful Developer Tool-Kits and more.

On the other hand, React has some significant disadvantages as well. This includes Client-Side Rendering which means that Web Applications developed with React cannot be scrapped or crawled over which makes it poor on Search Engine Optimization (SEO) Terms. React is also not supported by legacy browsers and the Documentation available for React, is particularly not sufficient for new Developers.

Build a MERN Stack Application

Compared to other Web Frameworks and Libraries, React has got a gentle learning curve and it has got plenty of resources besides the usual documentation which makes it good to develop Web Applications with. React has also got several other flavours like Next, which allows us to develop Applications with Server-Side Rendering, and Gatsby, which allows developing lightning-fast sites with React toolings.

Setting the React Project

Let’s first set up our React Project. To do that, you must have NodeJS and NPM installed on your Local Machine. If you have them installed, you can verify it with these simple commands:

$ node --version
$ npm --version

If you have installed NodeJS and NPM properly, you will get the following message:

Build a MERN Stack Application

Note that I’m using a Gitpod Development Environment, which is set inside a Linux Virtual Machine, which will not significantly affect any of your Development workflow.

Since we have our NodeJS and NPM set up and their versions verified, let’s install create-react-app which is the standard tool released by Facebook to install React Packages. This sole package will take care of setting up all your React Applications in future. Let’s install it using NPM:

$ npm install -g create-react-app

Once you have set create-react-app you can make use of it, to set your new React Application. Let’s name our application blog-frontend and make an all-new React Application using the boilerplate provided by create-react-app:

$ create-react-app blog-frontend

The Boilerplate Code would be all set by create-react-app automatically and you can now push in a simple command to kickstart the Application:

$ cd blog-frontend
$ npm start

The Development Server will kick-start at Port 3000 and you can view your application here:

You can open the src folder and take a look at all the files up there and explore the BoilerPlate Code a bit. Next we will be setting up our application and dividing the code into multiple pages and components that we can use to render our application.

Creating the Home Page

Now that we have st up our basic React Application, let’s move ahead now and create the Pages for our application. To understand the syntax, you should be a bit familiar with HTML and Javascript ES6. Create a folder under src and name it pages and create a file named: HomePage.js. It will consist of our code that will be rendered on the Home Page. Open the Page and put the following Code up there:

import React from 'react';

const HomePage = () => (
    <>
    <h1>Hello. This is my Homepage.</h1>

    <p>
    This is the HomePage for our Blog.
	Welcome to our Blog! This Blog brings to you 
	the latest updates on Technology and Development.
	This Home Page has been created for the purpose of 
	a tutorial on developing MERN Stack Application.
    </p>
    </>
)

export default HomePage;

We will first of all import react and define an Arrow Function which will consist of our Code in JSX Syntax. As you can see, we are making use of basic HTML Tags like Headings and Paragraphs to define the text that would be visible on the Page. All the Tags would be enclosed between React Fragments ( <> </> ) to render multiple elements. We will finally export the component which can be then called on the App.js file to render the Home Page.

Let’s go to App.js and make substantial changes. We will remove significant part of the Boilerplate Code and add this:

import React from 'react';
import HomePage from './pages/HomePage'

function App() {
  return (
    <div className="App">
      <HomePage />
    </div>
  );
}

export default App;

We have now imported the Home Page from the Pages Folder and used the Component inside the App Div which is finally rendered on our Development Server. If the App is compiled successfully, you may see a live preview like this:

Navigation in Application

Now that we have defined the Home Page, we can define multiple other pages in a similar manner. The easiest way to do that is by making use of React Router which gives us a handy way of implementing navigation in our Application. It allows us to display a certain page or slot depending on the current URL. Let’s install React Router by installing a simple package for our purpose:

$ npm install --save react-router-dom

This will install the React Router. Let’s now import Route and Browser Route from React Router into our app.js file. We will now wrap the entire component into Router Component so that we can keep all our components up to-date with our current URL. This is one of the biggest advantages of having React for handling Front-End Jobs. Let’s now write some code to implement the React Router in our Application:

import React from 'react';
import HomePage from './pages/HomePage';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom';

function App() {
  return (
      <Router>
              <div className="App">
                  <Route path="/" component={HomePage} exact />
              </div>
      </Router>

  );
}

export default App;

We have wrapped our App Div inside the Router Component and passed a Route with a path and component. This means that the HomePage would be displayed first whenever someone will land upon our Blog Application. To learn React Router with much depth, follow this blog to get a practical experience of working with React Router.

Creating Blog Pages

Now that we have created the Home Page and passed a Router that defines, whenever a user will land on the Blog, they will get to see the HomePage first. Now that we need some other pages as well, let’s create some more Page: AboutPage, ArticlesPage and ArticlesList. We can do the same stuff with each of these pages to add Content to our Application and then export it to our App.js file.

Populate each of the Pages with the content from the HomePage and export it accordingly to the App.js file. We will make use of React Router to create separate routes for each of these pages. We will be writing some CSS Code so that our Text does not span the whole Body and for that purpose we will open App.css and add the CSS:

#page-body {
    max-width: 700px;
    margin: auto;
    padding-top: 64px;
}

Once you add all the Dummy Content in the Pages, we can move ahead and create Routes for the Application. Let’s check out the Code for the same:

import React from 'react';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage';
import ArticlePage from './pages/ArticlePage';
import ArticlesList from './pages/ArticlesList';
import './App.css';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom';

function App() {
  return (
      <Router>
              <div id="page-body">
                  <Route path="/" component={HomePage} exact/>
                  <Route path="/about" component={AboutPage} />
                  <Route path="/article" component={ArticlePage} />
                  <Route path="/articles-list" component={ArticlesList} />
              </div>
      </Router>

  );
}

export default App;

Once you kick-start the Development Server, you can now see the various Pages displayed on separate Routes and the Page Text that has been centred and does not span the whole page.

Add Navigation Bar

Now that we have created Routes for all our Pages, we will be needing a Navigation Bar to navigate to various pages. For this purpose, we will be making use of the react-router link to link various pages. Let’s create a NavBar by creating a separate folder in src called components and adding a file called NavBar.js and pushing in the following code:

import React from 'react';
import { Link } from 'react-router-dom';

const NavBar = () => (
    <nav>
        <ul>
            <li>
                <Link to="/">Home</Link>
            </li>
            <li>
                <Link to="/about">About</Link>
            </li>
            <li>
                <Link to="/articles-list">Articles</Link>
            </li>
        </ul>
    </nav>
);

export default NavBar;

To style our Navigation Bar, we will make use of some CSS. Open up your App.css file and edit the CSS to look like this:

#page-body{
  max-width: 700px;
  margin: auto;
  padding-top: 64px;
}

nav {
  border-bottom: 4px solid black;
  text-align: center;
  position: fixed;
  top: 0;
  width: 100%;
  background: white;
}

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

nav li {
  display: inline-block;
  padding-top: 16px;
  padding-bottom: 16px;
}

nav a {
  text-decoration: none;
  color: black;
  font-weight: bold;
  padding: 16px 32px;
}

nav a:hover {
  background: black;
  color: white;
}

Let’s add the Navigation Bar in our App.js File and see how our Application looks like now:

import React from 'react';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage';
import ArticlePage from './pages/ArticlePage';
import ArticlesList from './pages/ArticlesList';
import './App.css';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom';
import NavBar from './components/NavBar'

function App() {
  return (
      <Router>
          <div className="App">
              <NavBar />
              <div id="page-body">
                  <Route path="/" component={HomePage} exact/>
                  <Route path="/about" component={AboutPage} />
                  <Route path="/article" component={ArticlePage} />
                  <Route path="/articles-list" component={ArticlesList} />
              </div>
          </div>
      </Router>

  );
}

export default App;

If the Application is successfully compiled, we can take a look at our Blog Application now:

Add Articles to our Application

Now that we have added the Home Page, About Page and finally the Articles Page, we will be moving ahead with creating the Page for showcasing our Articles. We will be making use of URL Parameters for this purpose where we use a id or a name to signify the page we are looking for. If React find a URL Parameter, it will pass a prop to the Components we have passed that the tells us to return the Component we are looking to render.

This Information is retrieved by the Component once the React Router passes a match to the component. This match props contains some useful information about the property we wish to render along with a property called params which contains the information about the name and parameter we wish to render.

To visualize this in real-time, we will create a seperate file known as article-content.js in pages where we can keep all the Content for our Articles. Let’s add some code here for our Article Content:

const articles = [
    {
        name: 'learn-react',
        title: 'What is React?',
        content: [
            `React is a Front-End Library developed by Facebook that relies on an all-new JSX 
			Syntax for rendering Web Applications with reusable components. React is now considered 
			to be one of the most influential Javascript Library (beside JQuery) to have put its mark 
			on the Web Development Community. The advantages of React are huge: Virtual DOM, Stable Code, 
			Proper Maintenance and powerful Developer Tool-Kits and more.`,
        ]
    },    {
        name: 'learn-node',
        title: 'What is NodeJS?',
        content: [
            `NodeJS is an efficient and lightweight runtime environment which is built on top of Chrome V8 
			Javascript Engine. Its support for an Event-Driven and Non-Blocking I/O Model makes it extremely 
			modular for developing Server-Side Interface for Applications.`,
        ]
    },     {
        name: 'learn-express',
        title: 'What is Express?',
        content: [
            `Express on the other hand is a framework that relies on NodeJS and abstracts most of the handlers 
			for our requests that we make to the Server-Side Interface. MongoDB is a Relational Database Management 
			System (RDBMS) which allows to index our Database Files and define Schemas that can be easily set up to 
			store our data in a flexible and secure manner.`,
        ]
    },  
];

export default articles;

In our article-content.js we have got three parts: name, title and content. The name property signifies the unique route where the article will be rendered while the title shows the title of the Article. On the other hand, content signifies the article content that is going to be displayed up there.

Let’s now add a 404 Page for our Application along with a Page to display all our Articles on the Blog Application. Create a separate file named NotFoundPage.js and add the following code there:

import React from 'react';

const NotFoundPage = () => (
    <h1>404: NOT FOUND</h1>
);

export default NotFoundPage;

Invalid Routes which don’t exist will fall back on 404 Page which can be a lot handy to route back to the previous pages. Let’s now add a separate file named ArticlesList.js in components to showcase the articles that are present on the Blog Application:

import React from 'react';
import { Link } from 'react-router-dom';
const ArticlesList = ({ articles }) => (
    <>
    {articles.map((article, key) => (
        <Link className="article-list-item" key={key} to={`/article/${article.name}`}>
        <h3>{article.title}</h3>
        <p>{article.content[0].substring(0,150)}...</p>
        </Link>
    ))}
    </>
);

export default ArticlesList;

We will make use of Link from React Router to link our articles according to the Article List Item on our Application properly. We will be passing articles prop to the component, and making use of the map to demonstrate all the Articles that are present on the Application along with a short content which is retrieved using substring() function.

Let’s now create another file named ArticlesListPage.js in pages which shows all the Articles in the Article-List:

import React from 'react';
import articleContent from './article-content.js'
import ArticlesList from '../components/ArticlesList';


const ArticlesListPage = () => (
    <>
    <h1>List of Articles</h1>
    <ArticlesList articles={articleContent} />
    </>
)

export default ArticlesListPage;

Now that, we have added all the required Pages and Components, let’s go to ArticlePage.js and checkout the Code that we need to show on our Page. We will be using the articleContent.js and ArticlesList to show the particular Blog, that the User has clicked on and show him other articles as well on the page, which the User would like to read. Let’s write the Code here:

import React from 'react';
import articleContent from './article-content.js'
import ArticlesList from '../components/ArticlesList';

const ArticlePage = ( {match} ) => {
    const name=match.params.name;

    const article=articleContent.find(article => article.name === name);

    const otherArticles=articleContent.filter(article=> article.name!==name)
    return (
        
    <>
        <h1>{article.title}</h1>
        {article.content.map((paragraph, key) => (
        <p key={key}>{paragraph}</p>
        ))}

        <h3>Other Articles:</h3>

    <ArticlesList articles={otherArticles} />
    </>

    );
}

export default ArticlePage;

We passed the matchProps as the props from the router and now we will make use of the same to get the name of the article and the title and content. We will define otherArticles as well to get the content for other particles by filtering them through.

Now that we have finished this Part, we can move ahead with making final changes to our application.

Final Touch

Now that we have made our Articles List modular, we will be adding final touch to our CSS File and App.js to make the Blog Application complete on the Client-Side. First we will head over to App.css and add some CSS to the articles list that we pass as a Component:

#page-body{
  max-width: 700px;
  margin: auto;
  padding-top: 64px;
}

nav {
  border-bottom: 4px solid black;
  text-align: center;
  position: fixed;
  top: 0;
  width: 100%;
  background: white;
}

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

nav li {
  display: inline-block;
  padding-top: 16px;
  padding-bottom: 16px;
}

nav a {
  text-decoration: none;
  color: black;
  font-weight: bold;
  padding: 16px 32px;
}

nav a:hover {
  background: black;
  color: white;
}

.article-list-item {
  text-decoration: none;
  color: black;
  padding: 16px 0 0 0;
}

.article-list-item p {
  padding-bottom: 32px;
  border-bottom: 2px solid black;
}

We can then move onto App.js and add our 404 Not Found Page to show in case the particular route does not exists. Let’s touch up the App.js file and see how our application would look like:

import React from 'react';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage';
import ArticlesListPage from './pages/ArticlesListPage';
import ArticlePage from './pages/ArticlePage';
import './App.css';
import {
  BrowserRouter as Router,
  Route,
  Switch,
} from 'react-router-dom'
import './App.css';
import NavBar from './components/NavBar';
import NotFoundPage from './pages/NotFoundPage';

function App() {
  return (
    <Router>
      <div className="App">
        <NavBar />
        <div id="page-body">
          <Switch>
            <Route path="/" component={HomePage} exact />
            <Route path="/about" component={AboutPage} />
            <Route path="/articles-list" component={ArticlesListPage} />
            <Route path="/article/:name" component={ArticlePage} />
            <Route component={NotFoundPage} />
         </Switch>
         </div>
      </div>
    </Router>
  );
}

export default App;

We have now finally finished up with our development with React, so let’s check out how our application looks like:

What’s next?

In Part II of the Blog Series, we will check out how we can make use of Application Programming Interfaces (APIs) developed using NodeJS and MongoDB to add more functionalities in the basic Client-Side Interface that has been developed for now. We will add the option to add Comments on a Blog and also upvote a particular Blog. In the last part of the series, we will be demonstrating how you can actually deploy the Application using Amazon Web Services (AWS) as our deployment option here.

The Code for the Front-End Implementation can be found here.

Also See : Learn React Router – A Complete Guide for Beginners

Click 👏 in the starting of the post if you like this article

Want to get regular updates of Free Courses, Internships & Job Opportunities and Technical Blogs to enhance your knowledge then join Dev Meet Telegram Channel or WhatsApp Group from below links

telegram channel link

LEAVE A REPLY

Please enter your comment!
Please enter your name here