The most fundamental problem in software development is complexity. There is only one basic way of dealing with complexity. Defeat Them in Detail: The Divide and Conquer Strategy. Look at the parts and determine how to control the individual parts, create dissension and leverage it.

In this article, we will see how to make our web application component-oriented and data-driven. We will continue from part1 where we learned how to build a full stack web application with flask, NPM, Webpack, and Reactjs.

You can get the project code we built in part1 here. Please clone it and follow the readme instruction to get it up and running . This blog will go through the implementation which can be found in this GitHub link here. However, you will gain more if you follow along this blog post.

Case Study: Creating our medium article

Fig 2: Medium articles displaying article images, number of claps, article title, article description, author image and author name

The aim of this article is to show you how to use the concept of component-oriented and data-driven in your React-Flask web app.

So we are going to build this simple medium articles web app which simply displays a list of articles including article images,

number of claps, article title, article description, author image, and author name.

Our web app is made up of three components: Header component, articleList component and article component. We will go through each component and will build it together. However, lets start by refreshing out mind on what component is all about.

What is Component?

A React component is a JavaScript class with a render method that returns a description of the component’s UI. So basically, components are self contained, concern-specific and are the building blocks of React UIs.

In a React application, everything is made of components. Developing applications using components allows a “divide and conquer” approach where no particular part needs to be especially complex. This makes it easy to create complex and more feature-rich components made of smaller components.

React component has some advantages which include:

Encourages separation of concerns

reusable

It is written in plain javaScript, instead of template languages or the HTML directives traditionally used for web application UIs.This enables React’s use of a full-featured programming language to render views a big advantage to the ability to build abstractions.

There are two ways to declare React components:

As ES6 classes

class HelloWorld extends React.Component{

render(){

return(

<p> Hello World </p>

);

}

}

ES6 introduced a class declaration syntax. ES6 classes are syntactical sugar over JavaScript’s protoype-based inheritance model.

You can read more about ES6 classes from the docs on MDN

2. Using the React.createClass() method

const HelloWorld = React.createClass({

render(){ return(<p> Hello World </p>)}})

If you have some familiarity with JavaScript, you will notice that the syntax of the return value doesn’t look like traditional JavaScript. It is JSX(JavaScript eXtension syntax), written by Facebook. Using JSX enables us to write the markup for our component views in a familiar, HTML-like syntax. In the end, this JSX code compiles to vanilla javaScript.

Our Component hierarchy

As said earlier, our app will contain 3 components. Below is the hierarchy of our components.

Fig 3: Hierarchy of our 3 components

Let us break apart the interface of our app into the different components classes:

Fig 4: Our App interface broken down into the different component classes

From Fig4 above, we see three different colors representing our different components.

The red color represents the ArticleList component . This component is the parent component.

. This component is the parent component. The blue color represents the Header component which will display the main header of the page.

which will display the main header of the page. The gold yellow color represents the article component which will display an article.

I think it is becoming boring. So enough with the repetition and theory. Lets code.

Article Component

Create the file hello_template/templates/static/js/components/Article.jsx and enter the code below

Semantic UI and Images: You will notice some few things from the code above. The styling and the source of the images. I am using semantic UI for styling. You can install this library as below:

1. Install Semantic UI React from npm or follow the documentation. Semantic UI React provides the JavaScript for our components

$ npm i semantic-ui-react --save

2. Add the Semantic UI CDN link in your hello_template/templates/static/index.html file

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css"></link>

Note: Every installations we will do with npm should be at a terminal opened in the hello_template/templates/static/ directory where package.json resides. Our Article.jsx is referencing images from public/images/article/ and public/images/avatars/ . You can download the image folder from the completed project Github here and include it in the hello_template/templates/public/ directory Or you can provide your own images.

Runing Article component

Let us run our component and see if all works fine. Since our web application is a flask-react web app, a rule of thumb for flask is that we have separate views for the different context of our application. We could still use the same view. But I decided to separate them so as to keep my work clean and easy to maintain. So we have two things to edit here. Our view and the route.

View: Views is flask specific and enables us to control how we interact with the web requests. Create the directory hello_template/templates/medium_articles/ . In this directory, create two files __init__.py and views.py . In the views.py file, enter the following code

from flask import render_template, Blueprint

medium_blueprint = Blueprint('medium_article',__name__)

def index():

return render_template("index.html") @medium_blueprint .route('/articlelist')def index():return render_template("index.html")

In this code as well as in any other code of this article, make sure you indent the code where appropriate

Our code does two important things

It creates a blueprint for our medium article

It listens to the URL ‘/articlelist’ and renders a template file index.html which is located in hello_template/templates/ directory

I explained blueprint in part 1.

Next, is to register our blueprint. Edit the hello_template/templates/__init__.py file as below:

from flask import Flask

app = Flask(__name__,

static_folder = './public',

template_folder="./static") from templates.hello.views import hello_blueprint

from templates.medium_articles.views import medium_blueprint

# register the blueprints

app.register_blueprint(hello_blueprint)

app.register_blueprint(medium_blueprint)

React Router: React Router is the most popular solution for adding routing to a React application.

Please refer to part 1 for a detail explanation about React Router and how to install it. Also, if you are working from the project from part 1 as recommended, React Router has already been installed

Edit the hello_template/templates/static/js/routes.js file as below:

import React from 'react';

import { HashRouter, Route, hashHistory } from 'react-router-dom';

import Home from './components/Home';

import ArticleList from './components/ArticleList'; // import more components //The exact param disables the partial matching for a route and makes sure that it only

// returns the route if the path is an EXACT match to the current url.

export default (

<HashRouter history={hashHistory}>

<div>

<Route exact path='/' component={Home} />

<Route path='/articlelist' component={ArticleList} />

</div>

</HashRouter>

);

From the code above, we did two things:

We imported ArticleList component

We provided a route path to the component.

ArticleList component

If you have noticed in our code above, we made use of articlelist instead of article. This is because our Article component will be contained in the Articlelist component.

So next, we will code our ArticleList component. Create the file hello_template/templates/static/js/components/ArticleList.jsx and enter in it the code below:

import React, { Component } from 'react';

import Article from './Article'; export default class ArticleList extends Component {

render() {

return (

<div className='ui unstackable items'>

<Article />

</div> )

}

}

We can notice two things from the above code

We imported the Article component

We called the Article component in our ArticleList component. Hence the ArticleList component is now a parent to the Article component

Run

Follow the instruction in part 1 under Running the App to get the project up and running then open this address http://127.0.0.1:5000/#/articlelist/ in to your favorite browser.

Fig 5: Our Web App running on Firefox Web Browser showing one article

Making Article Data-driven

So far we hard-coded our Article component with data which is not exactly ideal. So we need our Article component to be dynamically rendered based upon the data that we give it.

Create the file hello_template/templates/static/js/articleData.js and enter in it the code:

Our articleData.js contains a JavaScript object articleData.article which is an array of JavaScript object, each representing an article object. Each article has a unique id and a handful of properties including a title , description , clapps and more.

Using props

We want that our Article component no longer uses static, hard-coded attributes. Instead, we want it to be able to accept data passed down from its parent, ArticleList. Setting up our component structure in this way enables our ArticleList component to dynamically render any number of Article components that each have their own unique attributes. Data flow will look like this:

Fig 6: Data flow from parent to child

Data flow from parent to child in React through props. When a parent renders a child, it can send along props the child depends on. And we can access these properties inside a child component as this.props.

Let’s see this in action. Let’s modify ArticleList to pass down props to Article component. Let’s pluck the first object off of the articleData.article array and use that as data for a single article. Lets modify hello_template/templates/static/js/components/ArticleList.jsx

import React, { Component } from 'react';

import Article from './Article';

import articleData from '../articleData' export default class ArticleList extends Component {

render() {

const article = articleData.article[0];

return (

<div className='ui unstackable items'>

<Article article={article}/>

</div> )

}

}

From the code above, we imported our articleData.js , then we plucked the first object off of the articleData.article array, then we pass it as prop to our Article component.

Let’s modify Article component to access the props sent by the parent component(ArticleList)

import React, { Component } from 'react'; export default class Article extends Component {

render() {

const {article} = this.props

return (

<div className='item'>

<div className='image'>

<img src={article.productImageUrl} />

</div>

<div className='middle aligned content'>

<div className='header'>

<i className='large caret up icon' />

<b>{article.clapps}</b>

</div>

<div className='description'>

<a href={article.url}>{article.title}</a>

<p>{article.description}</p>

</div>

<div className='extra'>

<span>Published by: </span>

<img className='ui avatar image' src={article.submitterAvatarUrl} />

<span className='author'>{article.author} </span>

</div>

</div>

</div> )

}

}

From the code above, we access the article prop with this.props , then we replace all static data that was hard-coded with that received as props

If you refresh the browser, you will see nothing has changed. However, our app is now data-driven.

Rendering multiple article

If you had noticed, our articleData.js has 3 article object. It could be more and we will like to display all the articles.

We will have ArticleList generate an array of Article components. Each will be derived from an individual object in the articleData array. We will use map to do so. Let’s modify our hello_template/templates/static/js/components/ArticleList.jsx

import React, { Component } from 'react';

import Article from './Article';

import articleData from '../articleData' export default class ArticleList extends Component {

render() {

const articleSort = articleData.article.sort((a,b)=>(

b.clapps - a.clapps));

const articleCom = articleSort.map((a)=>(

<Article key={'article-'+a.id} article={a} />

)

);

return (

<div className='ui unstackable items'>

{articleCom}

</div> )

}

}

From the code above, we first sort the articles by number of clapps. Then we use map to create each Article component object passing as props their respective object derived from the articleData array. So our map will return an array of Article components and as required by map, each array object needs to have a unique key. So here we used each article object id as key.

Now, refresh the browser and you will see all the three articles displaying

Fig 7: Our web app displaying all three articles

Header Component

Our last component on the list is the Header component. This will display the header at the top of the page. Create the file hello_template/templates/static/js/components/Header.jsx and paste in it the following code:

import React, { Component } from 'react';

export default class Header extends Component {

render() {

return (

<div className='header-page'>

<img className='ui logo image' src={this.props.logo} />

<span className='header'>

Medium Articles

</span>

</div>

);

}

}

Our Header component simply displays a text ‘Medium Articles’ and a logo. We will notice that the logo ‘src’ has been gotten from the props as this.props.logo . This tells us that this component is a child component, in this case, a child component to the ArticleList component. Let us modify hello_template/templates/static/js/components/ArticleList.jsx to contain our Header component:

import React, { Component } from 'react';

import Article from './Article';

import articleData from '../articleData'

import Header from './Header'; export default class ArticleList extends Component {

render() {

const articleSort = articleData.article.sort((a,b)=>(

b.clapps - a.clapps));

const articleCom = articleSort.map((a)=>(

<Article key={'article-'+a.id} article={a} />

)

)

return (

<div className='container'>

<Header logo={articleData.logo}/>

<div className='ui unstackable items'>

{articleCom}

</div>

</div> )

}

}

To round up, let’s do some styling. Add the following CSS code in hello_template/templates/public/css/main.css

.header-page {

overflow: hidden;

background-color: #f1f1f1;

padding: 20px 10px;

text-align: center;

line-height: 25px;

color: black;

font-size:40px;

border-radius: 4px;

} .header{

color:black;

text-align: center;

font-size:40px;

background-color: #f1f1f1; }

.logo{

width:40px;

height: 30px;

clear:right;

}

.author{

color:#808080;

}

Now refresh your browser. If everything is working fine, your browser should display a page similar to Fig 2 . If not, please go through this article again and try to figure out what you might have missed

And that’s it. You’ve just turn your web application into Component-oriented and data-driven.

Thank you for your time, I would be updating this article accordingly. You can contribute by commenting, suggesting and sharing this article so that we can together, educate the world.

I will be releasing more articles like this, so make sure you follow me here on Medium so that you won’t miss any of my new releases.

Happy New Year

Fig 8: Happy New Year 2019

Let go of yesterday. Let today be a new beginning and be the best that you can, and you’ll get to where God wants you to be. May All Your Dreams and Wishes Come True, and May Prosperity Touch Your Feet. Wishing You a Happy New Year.