Advance UI development with JS MVC framework and React


Advance UI development with JS MVC framework and React

Recipe ID: hsts-r50


Recipe Overview

Writing code for reactive UI is a difficult task, as writing code to manipulate the DOM using JavaScript whenever the application state changes is difficult and it makes understanding the application difficult. Therefore, the MVC architecture was introduced, where we define the UI and application state separately, and the UI is updated automatically as the application state changes. MVC framework views have been concentrating on making the writing of code for reactive UIs easier but not increasing rendering performance, reusability, and ease of debugging. This is what React aims to solve. It not only makes writing code for reactive UI easier but also takes care of rendering performance, reusability, and ease of debugging.
In this recipe, we will cover the following topics:

Introducing React

React is a JavaScript library for building reactive UIs. We usually use jQuery or pure JavaScript to manipulate a reactive UI whenever the application state changes, which makes it difficult to reuse and understand the code. Instead, we can use React, which lets us declare how the UI behaves based on the application state, and it automatically updates the UI whenever the application state changes. There are lots of libraries and technologies, such as web components and templating engines, that aim to make the building of UIs easier, but React stands out from the crowd as it makes it easy to build reusable and high-performance reactive UIs.
React is also used as a view library because it is exactly what a view library is supposed to be. A view holds the UI of the application and defines how the UI changes based on the application state, that is, how the application state is displayed. As it's just a view library, it doesn't tell us how to manage, access, and mutate the application state. It can be used as the view layer in any kind of architecture and framework.
Remember that React is a library and not a framework such as Angular or Ember. Thus, React can be used with Angular to make Angular views better in terms of performance and reusability. For example, there is an AngularJS module named ngReact that lets React be used as a view in AngularJS.
Even the Flux architecture uses React as its view. We will learn more about Flux in the next recipe.
React is always used with a framework as it only defines the UI but doesn't tell us how to manage the application logic and state, just like a template library or web component is always used with a framework.
When building user interfaces using React, we don't write any HTML to build the UI like when using other frameworks and libraries; instead, we declare the DOM structure using JavaScript only. This programming style is what makes React able to implement various algorithms and technologies to achieve high rendering performance and reusability.
Before we get further into learning React, let's first set up a project to use it.

Setting up a basic React project

At the time of writing, the latest version of React was 0.14.7. This is the version this recipe uses. First, visit https://facebook.github.io/react/downloads. html to download React. Here, you will find two types of React builds, namely, production and development builds. The difference between these two build is that the development build is uncompressed and includes extra warnings, whereas the production build is compressed, includes extra performance optimizations, and strips all errors.
You should use the development build when your application is in the development phase. Once your application is ready for deployment, you should change to the production build.
Again, you will find two types of production and development build: one with add-ons and the other without. We will use the development version without add-ons.
You will find CDN links as well as links to download and enqueue React manually. React is composed of two files: react.js and react-dom.js. Download both of them manually.
Create a folder named react-demo and place both the files in it. Then, create a file
called index.html and put this code in it:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React Demo</title>

<script src="react.js"></script>
<script src="react-dom.js"></script>
</head>
<body>

<script>
//place React code here
</script>
</body>
</html>
Later on in this recipe, we will learn more about why React is composed of two files
and not one. For now, just ignore this.

Virtual DOM

A browser interprets HTML and creates a DOM. A DOM is a tree-like structure that defines the structure of the page. The browser then renders the DOM on the page. The DOM API is what we use to manipulate the DOM. When we manipulate it, the browser re-renders the manipulated parts.
The problem is not with how the DOM works, but how we programmatically alter it. Manipulating nodes of a DOM requires expertise; otherwise, we could often end up re-rendering lots of nodes unnecessarily, which would result in poor rendering performance.
For example, imagine we have a large list of products in an e-commerce website. We also have a filter widget to filter the items. When we change the values in the filter widget, the list items are reloaded and the complete list is re-rendered, which requires a lot of manipulation to the DOM and can result in bad rendering performance. To get better performance, we can actually manipulate only specific parts of the list, such as product titles, image, and cost. But writing code for this is going to be hard.
Let's take another example. If you are using ng-repeat to display a list, then adding a new item to the list will cause the complete re-rending of the list. So, if Facebook or Instagram had used ng-repeat, then whenever we scrolled down, the whole set of posts would have been re-rendered. The solution to this problem is instead of using ng-repeat, which re-renders the whole list, we can append a new post to the end of the list using jQuery or pure JavaScript. But if you want to maintain the posts that are being displayed, then you will end up writing some more complex code.
Due to these kinds of problem, virtual DOM was introduced. Virtual DOM makes sure that anyone can write complex reactive UI code without worrying about performance. Virtual DOM is the secret that React implements to achieve rendering performance.

A virtual DOM is an abstract version of the real DOM, that is, a description of the real DOM. Virtual DOM elements are just JavaScript objects whereas real DOM elements are real UI elements. Virtual DOM is much faster as it's just a JavaScript data structure and manipulating it doesn't automatically re-render the UI. Earlier,
I said that in React, you don't write any HTML but instead declare the structure of the DOM. Actually, you declare the structure of the virtual DOM, not the real DOM. React keeps the real DOM in sync with virtual DOM. Whenever the application state changes to update the UI, React uses complex algorithms to compare the real DOM with the virtual DOM and finds as few mutations as possible for the real DOM to sync with the virtual DOM. We will later see how these algorithms actually find the difference and mutate the real DOM. For example, if we have a list in the virtual DOM and we remove the list and add a new list with just an extra item, then, only the new item is rendered when synced with the real DOM, not the whole list.
Let's look at some example code to print Hello World using React. Inside the index. html body tag, place this code:
<div id="container1"></div>
We are going to display Hello World inside this div element. Place this code in the script tag of the index.html file to display Hello World:
var helloBold = React.createElement("b", {}, "Hello"); var worldItalic = React.createElement("i", {}, " World");
var helloWorld = React.createElement("a", {href: "#"}, helloBold, worldItalic);

ReactDOM.render(helloWorld, document.getElementById("container1"));
Here is how the code's output looks:
JS MVC and React coding

Let's understand how the code works.
React.createElement is used to create an object of a ReactElement interface. A ReactElement object is a light, stateless, and virtual representation of a real DOM element, but it's not a real DOM element. It's a virtual DOM, basically.
ReactElement and real DOM elements are of different interfaces. The first parameter of React.createElement can be an HTML tag name or an object of a ReactClass interface. We will learn more about ReactClass later on. The second argument is an object containing attributes of the HTML tag or properties of the ReactClass object. And then, we can pass an infinite number of arguments, which can be strings, ReactElement objects, or ReactClass objects. All the arguments after the second argument are treated as children of the ReactElement object that's going to be created. If the children are dynamically decided, then you can provide an array as  the third argument.
Here, we created three ReactElement objects. helloWorld is an anchor tag with helloBold and worldItalic as its children. We assigned the href attribute of the anchor tag to #.
ReactDOM.render is used to render ReactElement objects in the real DOM. ReactDOM.render takes a ReactElement object as first argument, and the second argument is the reference to the container element in the real DOM inside which we want to add to the ReactElement.
Here, we've rendered the anchor tag inside the container element.

 

In the beginning, it may feel as if ReactElement and real DOM elements are just created in different ways and their interface is the same, but this is not true.
Here are a few differences:

Components

You can use React using only ReactElement objects, but to take advantage of React, you have to use React components. ReactElement objects are stateless and
immutable and therefore useless for building reactive UIs. Also, they don't provide a structured mechanism for UI reusability.
A React component is a reusable custom tag that is mutable and encapsulated with an embedded state, that is, changes to the state or properties will mutate the UI. For example, we can have a component named clock that takes the current time as an attribute and displays a clock with the passed time. Another exchange could be a Bitcoin price component that displays Bitcoin prices in real time.
A component state is internal to the component. It's created and mutated inside the component. However, the properties of a component cannot be mutated inside the component; rather, they can be mutated by the code that created the component instance.
You can break your complete UI into components—this is the style of coding that's recommended when building a UI using react. You can use components inside components as well. Before we get further into components, let's rewrite the previous Hello World code using components.
Inside the index.html body tag, place this code:
<div id="container1"></div>
We are going to display Hello World inside this div element. Place this code in the script tag of the index.html file to display Hello World:
var anchorWithBoldItalic = React.createClass({ render: function() {
return React.createElement( "a",
{href: this.props.href},
React.createElement("b", {}, this.props.boldText), React.createElement("i", {}, this.props.italicText)
);
}
});

var HelloWorld = React.createElement(anchorWithBoldItalic, {href: "#", boldText: "Hello", italicText: " World" });

ReactDOM.render(HelloWorld, document.getElementById("container2"));

Here is the output of the previous code:
JS MVC and React coding

Here is how the code works:

to access its properties.

rendered it using ReactDOM.render.

 

One-way data binding

In the previous subsection, I stated that a component has an enclosing nature. Whenever we make changes to the state, the component is rendered. Components also let you register UI event handlers, and you can mutate the state inside the event handlers too.

React lets you manage, access, and mutate UI state but not application state. The difference between UI state and application state is that the UI state represents the data that's used to manipulate the UI whereas the application state represents the data that's displayed in the UI. For example, let's assume that you have a comment box. The comments in the comment box are the application state, and the View more comments button is the UI state, which may or may not be displayed, depending on whether there are any more posts.
Data binding between a UI and its state is only one-way. This means that user actions on the UI cannot alter the UI state directly, but the UI state can alter the UI.
It may seem as if this were a limitation as AngularJS and other popular frameworks provide two-way data binding, but this is actually a feature. This feature makes it easier to understand and debug applications.
Many developers tend to use UI state as application state, but for complex and large apps, this will cause issues and make it difficult to build the application.
Let's look at an example of how to use component state by building a button that hides/shows a box when clicked on.
Place this code in the <body> tag of the index.html file:
<div id="container3"></div>
We will display the component inside this container element. Place this code inside the script tag:
var hideShowBoxButton = React.createClass({ getInitialState: function(){
return {
display: "inline-block"
}
},
handleClick: function(){ if(this.state.display == "inline-block")
{
this.setState({display: "none"});
}
else
{
this.setState({display: "inline-block"});
}
},
render: function(){
return React.createElement( "div",
{},
React.createElement( "a",
{href: "#", onClick: this.handleClick}, "Click to Show/Hide"
),
React.createElement( "span",
{
style: {
display: this.state.display, height: 30,
width: 30, backgroundColor: "red"
}
}
)
);
}
});

ReactDOM.render(React.createElement(hideShowBoxButton), document.getElementById("container3"));
This is the output of the previous code:
JS MVC and React coding

This is how the code works:

the virtual DOM with the real DOM and mutating only the required DOM elements. This is how it achieves rendering performance.

Isomorphic UI development

Isomorphic development is where we can use the same code in both the frontend and backend.
Till now, we've seen how to use React in the frontend to build reactive UI, but the same React code can also be used in the backend. When used in the backend, React outputs HTML and doesn't provide any kind of UI performance advantage or reactivity.
The isomorphic nature of React is one of the things that make it so popular and powerful. It has made many things easier. For example, it makes it easier to prevent FOUC by letting us pre-render the page in the backend, and then in the frontend: the same components will just add event bindings.
React code not only executes in Node.js but can also be executed in PHP, Ruby,
.NET, and some other major backend languages.
Due to the fact that React can be used in both the frontend and backend, the React developer team decided to split React into two files: React core and another part that is specific to the executing environment. That's why when we included React in our HTML file earlier, we included two files. The React core contains React. createElement, React.createClass, and so on whereas the React DOM contains ReactDOM.render and so on.
Let's look at an example of how to use React in Node.js by creating and displaying the previous hello world component in Node.js. Create a directory named React- Server-Demo. Inside it, create files named app.js and package.json.

Inside the package.json file, place this code:
{
"name": "React-Server-Demo", "dependencies": {
"express": "4.13.3",
"react": "0.14.7",
"react-dom": "0.14.7"
}
}
Then, run npm install to download the Express and React modules. Now, in the
app.js file, place the following code and run the node app.js command:
var React = require("react");
var ReactDOMServer = require("react-dom/server"); var express = require("express");
var app = express();

var anchorWithBoldItalic = React.createClass({ render: function() {
return React.createElement( "a",
{href: this.props.href},
React.createElement("b", {}, this.props.boldText), React.createElement("i", {}, this.props.italicText)
);
}
});

var HelloWorld = React.createElement(anchorWithBoldItalic, {href: "#", boldText: "Hello", italicText: " World" });

app.get("/", function(httpRequest, httpResponse, next){
var reactHtml = ReactDOMServer.renderToString(HelloWorld); httpResponse.send(reactHtml)
})

app.listen(8080);
Now, open http://localhost:8080/ in your browser; you'll see this output:
JS MVC and React coding

This is how the code works:

 

Getting started with JSX

Writing JavaScript to define a tree-like structure and attributes while building UI using React is difficult and also makes it difficult to understand the UI. So, the React team came up with an alternative syntax to write React code, which is easier to write and understand. This alternate syntax is called JSX. JSX stands for JavaScript syntax extension. It looks similar to XML. Files that contain JSX code have the.jsx extension.

Compiling JSX

Of course, browsers and server-side engines cannot understand and interpret JSX; therefore, we need to compile JSX into pure JavaScript before using it.
There are various open source JSX compilers. You can find the list at https:// github.com/facebook/react/wiki/Complementary-Tools#build-tools. The most popular and recommended compiler for JSX is Babel. Babel can be installed (https://babeljs.io/docs/setup/), we can use the Babel compiler online (https://babeljs.io/repl/), and we can also embed the Babel compiler in our HTML page so that it compiles in the browser.

 

For the purpose of demonstration, we will embed the Babel compiler in our HTML page. Compiling takes time, so in production sites, you should never embed the compiler in web pages; instead, you should precompile and serve JSX code.
To embed the Babel compiler in a webpage, visit https://cdnjs.com/libraries/ babel-core and download the Babel core. These are CDN links, so they can be embedded directly, but let's download and embed them in our webpage. Download the browser.min.js file and place it in the react-demo directory. And then, embed it in the index.html page by placing the following code in the <head> tag:
<script src="browser.min.js"></script>
Now, create a new <script> tag at the end of the body tag and set the type attribute to text/babel so that the Babel compiler knows which code to compile. Here is how the code should look:
<script type="text/babel">
</script>
From now on, all the JSX code will be placed in this script tag.

 

JSX syntax

Let's rewrite the data-binding example code using JSX syntax. Place this code in the body tag to create a new container element:
<div id="container4"></div>
Here is the JSX code. Place it in the script tag that will be compiled by Babel:
var HideShowBoxButton = React.createClass({ getInitialState: function(){
return {
display: "inline-block"
}
},
handleClick: function(){ if(this.state.display == "inline-block")
{

this.setState({display: "none"});
}
else
{
this.setState({display: "inline-block"});
}
},
render: function(){ var boxStyle = {
display: this.state.display, height: 30,
width: 30, backgroundColor: "red"
};

return (
<div>
<a href="#" onClick={this.handleClick}>Click to Show/Hide</a>
<span style={boxStyle}></span>
</div>
)
}
});

ReactDOM.render(<HideShowBoxButton />, document.getElementById("container4"));
The output of the code is as follows:
JS MVC and React coding

Before we see how this code works, let's look at its compiled version:

 

var HideShowBoxButton = React.createClass({ displayName: "HideShowBoxButton",

getInitialState: function getInitialState() { return {
display: "inline-block"
};
},
handleClick: function handleClick() {
if (this.state.display == "inline-block") { this.setState({ display: "none" });
}
else
{
this.setState({ display: "inline-block" });
}
},
render: function render() { var boxStyle = {
display: this.state.display, height: "30px",
width: "30px", backgroundColor: "red"
};
}
});

return React.createElement( "div",
null, React.createElement(
"a",
{ href: "#", onClick: this.handleClick }, "Click to Show/Hide"
),
React.createElement("span", { style: boxStyle })
);

ReactDOM.render(React.createElement(HideShowBoxButton, null), document.getElementById("container4"));
This compiled version will give you a basic idea of how JSX syntax works. Let's understand how the previous JSX code works.
In a nutshell, JSX is used to write the React.createElement method in XML-like syntax. The XML tag name is the first argument, the attributes are the second argument, and finally, the child elements are the other arguments of React.createElement.

If a JSX tag name starts with a lowercase letter, it's an HTML tag, whereas if it starts with a capital letter, it's a component. So here, we made the component name start with a capital H. Had we used a small H, it would have been treated as an HTML tag, and <hideShowBoxButton></hideShowBoxButton> would have been inserted into the page, which would have rendered nothing.
In the HideShowBoxButton component, except the render method code, everything else is the same. We rewrote the render method using JSX syntax.
JSX provides {} braces to wrap JavaScript expressions while assigning them to attributes or using them as child elements. Here, we've assigned JavaScript expressions to onClick and style attributes.
Finally, we created an instance of the component using JSX syntax.
In the compiled code, you will find a displayName property in the object passed to React.createClass. The displayName property is used for debugging. If not set, it's set to the component name while compiling.

Digging into components

Let's dig further into components and master them. We'll look at component composition and ownership. Learning this will help us build complex reactive UIs that are easier to manage.

Component composition

Composability is a feature that lets you use a component inside another component's render method.
Let's look at a basic example of component composition. First, create a new container element. To do so, place the following code in the body tag:
<div id="container5"></div>
Here is the component composition example code. Place this code in the script tag that's compiled by Babel:
var ResponsiveImage = React.createClass({ render: function(){

var imgWidth = { width: "100%"
}

return (
<img src={this.props.src} style={imgWidth} />
)
}
})

var Card = React.createClass({ render: function(){
var CardContainerStyle = { maxWidth: 300, backgroundColor: "grey"
}

return (
<div style={CardContainerStyle}>
<h4>{this.props.heading}</h4>
<ResponsiveImage src={this.props.src} />
</div>
)
}
})

ReactDOM.render(<Card src="http://placehold.it/350x150" heading="This is a Card Header" />, document.getElementById("container5"));
This is the output of the code:
JS MVC and React coding

 

Here, we've created two different components. Inside the Card component, we are using the ResponsiveImage component to display a responsive image in it.

Component ownership

When components are used inside other components' render methods, they are said to have an owner-ownee relationship and not a parent-child relationship. Component X is said to be the owner of component Y if component X created an instance of component Y in its render method.

For example, in the previous code, the Card component is the owner of the
ResponsiveImage component and <div> is the parent of ResponsiveImage.
If we place a component instance inside the opening and closing tags of a component instance, then they are said to be in a parent-child relationship. The parent can access its children by using the this.props.children object. React also provides utility functions to make working with children easier. You can find the utilities  at https://facebook.github.io/react/docs/top-level-api.html#react. children.

Reconciliation

Reconciliation is the process by which React updates the DOM whenever the state changes. React doesn't re-render everything from scratch when the state changes; instead, it first finds whether a mutation is required by comparing the new virtual DOM with the old one, and if there is a difference, it compares the new virtual DOM with the real DOM and makes the necessary mutations.

Let's see how exactly reconciliation happens by looking at an example. Suppose this is the initial render:
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
If we remove Item 1 from the state, then the render will change to this:
<ul>
<li>Item 2</li>
</ul>
React algorithms compare DOM items one by one, and whenever they find a difference between two nodes, they make mutations. So here, React will remove the Item 1 list item by changing the text of the first list item and removing the last one. This process is much faster than removing both the list items and adding a new list item, which is what ng-repeat does and what we used to do using JavaScript.
If the node type is different, React will treat them as two different subtrees, throw away the first one, and build/insert the second one. For example, if we change <ul> to <ol>, the complete <ul> tree will be deleted.
This behavior is fine until you add new items to the end of the list or modify them. In case you add new items to the beginning or in between the list, you will start facing rendering performance issues. To understand the issue, let's take an example. Let's add Item 0 to the beginning. Now, the render will look like this:
<ul>
<li>Item 0</li>
<li>Item 1</li>
<li>Item 2</li>
</ul>
Here, while reconciling, React will first change the text of the first list item to Item 0, then change the text of the second list item to Item 1, and finally will add a new list item and assign its text to Item 2 instead of simply adding a new list item to the beginning of the list. This behavior makes the rendering actually slower.
React does provide a way to get around this kind of issue as well. It lets us uniquely identify each child by assigning it a unique key. When React reconciles the keyed children, it will ensure that any child with a key will be reordered (instead of being mutated) or destroyed (instead of being reused). A key is assigned using the key attribute.

Let's look at an example of how to create keyed children. Here is the code to create a new container element. Place this code in the body tag:
<div id="container6"></div>
Here is the React code for creating keyed children:
var DynamicList = React.createClass({ getInitialState: function(){
return {
results: this.props.results
}
},
handleClick: function(){
var results = this.state.results; var firstId = results[0].id - 1;
var firstValue = results[0].value - 1;

results.unshift({id: firstId, value: firstValue}); this.setState({results: results});
},
render: function(){ return (
<div>
<a href="#" onClick={this.handleClick}>Click to add new item</a>
<ul>
{this.state.results.map(function(result) {
return <li key={result.id}> {result.value} </li>;
})}
</ul>
</div>

)
}
})

var results = [{id: 1, value: 1}, {id: 2, value: 2}];

ReactDOM.render(<DynamicList results={results} />, document.getElementById("container6"));
Here is the output of the code:
JS MVC and React coding

Here, when the anchor element is clicked on, a new object is added to the beginning of the result array. As the state changes, the list is re-rendered. While rendering, React will reorder the list items and add new list items to the beginning instead of mutating them.

 

Default component property values

React lets you define default values for properties in a very declarative way.
The default value is used if the parent does not pass a property.
Default values are returned by a method getDefaultProps, which is a member of the object passed to React.createClass. Here is some sample code:
var ComponentWithDefaultProps = React.createClass({ getDefaultProps: function() {
return {
value: 'default value'
};
}
});

 

Component life cycle methods

Various methods are executed at specific points in a component's lifecycle. Let's look at them.

 

componentWillMount()

The componentWillMount() method is invoked once immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

componentDidMount()

The componentDidMount() method is invoked only on the client side. It is invoked only once after initial rendering has occurred.

componentWillReceiveProps(nextProps)

Directly mutating the properties passed to a component will have no effect because there is no way for React to find value changes as it doesn't watch the properties directly. But sometimes, it is possible for React to predict property value changes, and in that case, it calls the componentWillReceiveProps method, if it exists, with the new property values as its parameters, and it also re-renders the component.
For example, if we change the state of the owner of a component, then that sends a signal that the properties of the components it owns might have changed, so it calls the componentWillReceiveProps method and re-renders the components it owns.
Let's look at an example to demonstrate the componentWillReceiveProps method. We will create a button whose value increments every second. Here is the code to create a new container element. Place it in the body tag:
<div id="container7"></div>
Here is the code for our example. Place this code in the script tag that will be compiled by Babel:
var ButtonComponent = React.createClass({ componentWillReceiveProps: function(nextProps){
console.log("Text changed to " + nextProps.text);
},
render: function(){ return (
<button>{this.props.text}</button>
)
}
})

var ButtonHolderComponent = React.createClass({ componentDidMount: function(){
setInterval(function(){ this.setState({
text: this.state.text + 1
});
}.bind(this), 1000)
},
getInitialState: function(){ return {
text: 1
}
},
render: function(){ return (
<ButtonComponent text={this.state.text} />
)
}
})

ReactDOM.render(<ButtonHolderComponent />, document.getElementById("container7"));
Here is the output of the code:
JS MVC and React coding

In the code, we are changing the state of the owner every second after the initial rendering has occurred. Whenever the state changes, the
componentWillReceieveProps object of ButtonComponent is called. Inside the componentWillReceieveProps object, we can use this.props to access the previous values of the properties. The button is rendered whenever its owner's state changes.
Remember that componentWillReceieveProps is called before the component is re-rendered, so we can make any state changes we want inside it.

 

shouldComponentUpdate(nextProps, nextState)

The shouldComponentUpdate(nextProps, nextState) method is called before the render method is called, that is, before rendering happens. If this method returns false, then rendering is skipped.
Remember that this method is not called before forced updates or initial rendering.

 

componentWillUpdate(nextProps, nextState)

The componentWillUpdate(nextProps, nextState) method is invoked immediately before rendering when new props or state are being received. This method is not called for the initial render.
Note that you cannot use this.setState inside this method.

componentDidUpdate(prevProps, prevState)

The componentDidUpdate(prevProps, prevState) method is invoked immediately after the component's updates are flushed to the real DOM. This method is not called for the initial render.

componentWillUnmount()

The componentWillUnmount() method is invoked immediately before a component is unmounted from the real DOM.

 

Mixins

There are times when multiple components share the same code; in such cases, we can use mixins instead of writing the same code again and again.
A mixin is an object that holds component methods that can be easily plugged in to any component.
Let's look at an example to demonstrate mixins. Here is the code to create a new container element. Place it in the body tag:
<div id="container8"></div>
Here is the code for our example. Place it in the script tag that will be compiled by Babel.
var Mixin1 = { componentWillMount: function(){
console.log("Component will mount now");
}
}

var Mixin2 = { componentDidMount: function(){
console.log("Component did mount");
}
}

var HeadingComponent = React.createClass({ mixins: [Mixin1, Mixin2],
render: function(){
return <h1>React is Awesome</h1>
}
});

ReactDOM.render(<HeadingComponent />, document.getElementById("container8"));
This is the output of the code on the page:
JS MVC and React coding

 

And this is the output on the console:
JS MVC and React coding

Here, we've created two mixins and added them to HeadingComponent. These mixins can be used in any number of methods. Mixins simply increase code reusability.

Using Refs

Refs are used inside components to return references to real DOM elements rendered by React. So, instead of assigning an id or class value to elements, we can assign refs. It's easier to get references to real DOM elements using refs than id or class attributes.
Let's look at a basic example of how to use refs by creating a form. First, create a container element and place it inside the body tag. Here is the code:
<div id="container9"></div>
Here is the code for the form, which uses refs:
var FormComponent = React.createClass({ clicked: function(){
console.log(this.refs.myInput.value);
},
render: function(){ return (
<div>
<input type="text" placeholder="Write Something" ref="myInput" />
<input type="button" value="Click to Submit" onClick={this.clicked} />
</div>

)
}
})

ReactDOM.render(<FormComponent />, document.getElementById("container9"));

 

The output of this code on the webpage is as follows:
JS MVC and React coding

If we enter Hello World in the text field and click on the button, then the output of
the console is this:
Hello World
In the previous code, we're assigning a ref attribute to the button element. To refer to the button in the methods of the component, we use this.refs.

ReactDOMServer.renderToStaticMarkup

Earlier in this recipe, we used React on the server side to generate HTML. The HTML generated by React on the server and client side contains data-reactid attributes, which are used by React internally. On the client side, it makes sense to have data-reactid, as it is used during reconciliation and other processes and features.
You must be wondering what the point of adding this attribute on the server side is. Actually, it is added so that if you call ReactDOM.render() on the client side on a node that already has React server-rendered markup, React will preserve it and only reconcile it.
If you don't want data-reactid attributes to be generated on the server side, you can use renderToStaticMarkup instead of renderToString.

Summary

In this recipe, we learned React up to an intermediate level by covering in depth its features and components, JSX, using it for server-side rendering, reconciliation, and so on. We also learned miscellaneous features such as mixins and refs. Now, you should have a basic understanding of how and when to integrate React into your websites.

Here are related articles if you wish to learn more advance topics for web development:

Best practices for securing and scaling Node.JS applications
Comprehensive overview of Angular 2 architecture and features
How Bootstrap 4 extensible content containers or Cards work
Comprehensive guide for migration from monolithic to microservices architecture
Comprehensive overview of Bootstrap 4 features for user interface customizations
Intro to functional reactive programming for advance js web development
Using advance js and webrtc for cross browser communications in real time
Intro to real-time bidirectional communications between browsers and webSocket servers

Junior or senior web developers can also explore career opportunities around blockchain development by reading below articles:

Blockchain Developer Guide- Comprehensive Blockchain Ethereum Developer Guide from Beginner to Advance Level
Blockchain Developer Guide- Comprehensive Blockchain Hyperledger Developer Guide from Beginner to Advance Level

Here are more hands-on recipes for advance web development:
Build advance single page application with Angular and Bootstrap
Develop microservices with monolithic core via advance Node.JS
Develop server-side applications using microservices with Seneca.JS
Develop advance JavaScript applications with functional reactive programming
Develop advance webcam site using Peerjs and Peerserver with Express.JS
Develop advance bidirectional communication site with websockets and Express.JS

This tutorial is developed by Narayan Prusty who is our senior Blockchain instructor.

Related Training Courses

Hands-on Node.JS, MongoDB and Express.js Training
Advance JavaScript, jQuery Using JSON and Ajax
Developing Web Applications Using Angular.JS
Design websites with JavaScript React in 30 hours
Blockchain Certified Solution Architect in 30 hours
Advance JavaScript, jQuery Using JSON and Ajax
Introduction to Python Programming
Object Oriented Programming with UML


Private and Custom Tutoring

We provide private tutoring classes online and offline (at our DC site or your preferred location) with custom curriculum for almost all of our classes for $50 per hour online or $75 per hour in DC. Give us a call or submit our private tutoring registration form to discuss your needs.


View Other Classes!