0

Learning ReactJS and Bootstrap

There are many different ways to build modern web application with JavaScript and CSS, including a lot of different tool choices, and a lot of new theory to learn. In this article we will introduce you to ReactJS and Bootstrap which you will likely come across as you learn about modern web app development. They both are used for building fast and scalable user interfaces. React is famously known as a V (view) in MVC when we talk about defining ‘M’ and ‘C’ we need to look somewhere else or we can use the other’s frameworks like Redux and Flux to handle the remote data.

The best way to learn code is to write code, so once you read this article you have better understanding how easy it is to get up and running with Bootstrap and ReactJS, we’re going to cover theory of ReactJS and Bootstrap and also will see lifecycle of React components,JSX,Benefits,Responsive Layout and Redux Architecture.

ReactJS

React (sometimes styled React.js or ReactJS) is an open-source JavaScript library which provides a view for data rendered as HTML. Components have been used typically to render React views which contain additional components specified as custom HTML tags. React gives you a trivial virtual DOM, powerful views without templates, unidirectional data flow and explicit mutation. It is very methodical in updating the HTML document when data changes; and a clean separation between components on a modern single-page application.

As your app comes into existence and develops, it’s advantageous to ensure that your components are used in right manner and React app consists of Reusable components, which makes code reuse, testing, and separation of concerns easy.

ReactJS is not only “V” in MVC, it has stateful components, it handles mapping from input to state changes, and it renders components. In this sense, it does everything that an MVC does.

Let’s look at React’s component Life Cycle and it’s different levels.  

Bootstrap

Bootstrap is open-source front-end framework maintained by twitter for developing responsive websites and web application. It includes HTML, CSS, and JavaScript code to build user interface components. It’s faster and easy way to develop powerful mobile first user interface.

Bootstrap grid system allows us to create responsive 12 column grids, layout and components. It includes predefined classes for easy layout options (fixed-width and full width). Bootstrap have pre-styled dozen reusable components and custom jQuery plugins like Button, Alerts, Dropdown, Modal, Tooltip Tab, Pagination, Carousal, Badges, icons and many more.

Bootstrap package includes the compiled and minified version of css and js for our app we just need css bootstrap.min.css and fonts folder. This stylesheet will provide you the look and feel of all components, responsive layout structure for our application. In previous version bootstrap included icons as image but in version 3 they replaced have icons as fonts. We can also customize the bootstrap css stylesheet as per the component featured in our application.

React-Bootstrap

The React-Bootstrap JavaScript framework is similar to Bootstrap rebuilt for React. It’s a complete re-implementation of the Bootstrap front-end reusable components in React. React-Bootstrap has no dependency on any other framework, such as bootstrap.js or jquery. It means that if you are using React-Bootstrap then we don’t need to include the jquery in your project as a dependency. Using React-Bootstrap, we can be sure that, there won’t be external JavaScript calls to render the component which might be incompatible with the React DOM render. However, you can still achieve the same functionality and look and feel as Twitter Bootstrap, but with much cleaner code.

Benefits of React – Bootstrap

  1. Compare to Twitter Bootstrap, we can import required code / component.
  2. It saves a bit of typing and bugs by compressing the Bootstrap.
  3. It reduces typing efforts and, more importantly, conflicts by compressing the Bootstrap.
  4. We don’t need to think about the different approaches taken by Bootstrap versus. React
  5. It is easy to use
  6. It encapsulates in elements
  7. It uses JSX syntax
  8. It avoids React rendering of the virtual DOM
  9. It is easy to detect DOM changes and update the DOM without any conflict
  10. It doesn’t have any dependency on other libraries, such as jQuery

Bootstrap Grid system

Bootstrap is based on a 12- column grid system which includes a powerful responsive structure and a mobile first fluid grid system that allows us to scaffold our web app with very few elements. In Bootstrap, we have a predefined series of classes to compose of rows and columns, so before we start we need to include the <div>tag with the “container” class to wrap our rows and columns. Otherwise, the framework won’t respond as expected because Bootstrap has written CSS which is dependent on it, below is HTML structure of “container” class <div> tag:

This will make your web app the centre of the page as well as control the rows and columns to work as expected in responsive.

There are four class prefixes which help to define the behaviour of the columns. All the classes are related to different device screen sizes and react in familiar ways. The following table from http://getbootstrap.com  defines the variations between all four classes:

  Extra small devices Phones (<768px) Small devices

 Tablets (≥768px)

Medium devices

Desktops (≥992px)

Large devices

 Desktops (≥1200px)

Grid behavior Horizontal at all times Collapsed to start, horizontal above breakpoints
Container width None (auto) 750px 970px 1170px
Class prefix .col-xs- .col-sm- .col-md- .col-lg-
# of columns 12
Column width Auto ~62px ~81px ~97px
Gutter width 30px (15px on each side of a column)
Nestable Yes
Offsets Yes
Column ordering Yes

React Components

ReactJS is basically based on a build modular, with encapsulated components that manage their own state so it will efficiently update and render your components when data changes. In React, components logic is written in JavaScript instead of templates so you can easily pass rich data through your app and manage the state out of the DOM.

Using .the render() method, we are rendering a component in react that takes input data and returns what you want to display. It can either take HTML tags (strings) or React components (classes).

Let’s take quick look at examples of both:

In this example, we are passing HTML as a string into the render method which we have used before creating the <Navbar>:

In the preceding example, we are rendering the component, just to create a local variable that starts with an upper-case convention. Using the upper versus lower case convention in React’s JSX will distinguish between local component classes and HTML tags. So, we can create our React elements or components in two ways: either we can use Plain JavaScript with React.createElement or React’s JSX.

React.createElement()

Using JSX in ReactJS is completely optional for creating the react app. As we know, we can create elements with React.createElement which take three arguments: a tag name or component, a properties object, and a variable number of child elements, which is optional.

In the preceding example, we have used React.createElement to generate a ul li structure. React already has built-in factories for common DOM HTML tags.

JSX in React

JSX is extension of JavaScript syntax and if you observe the syntax or structure of JSX, you will find it similar to XML coding.

JSX is doing pre-processor footstep which adds XML syntax to JavaScript. Though, you can certainly use React without JSX but JSX makes react a lot more neat and elegant. Similar like XML, JSX tags are having tag name, attributes, and children and in that if an attribute value is enclosed in quotes that value becomes a string.

The way XML is working with balanced opening and closing tags, JSX works similarly and it also helps to understand and read huge amount of structures easily than JavaScript functions and objects.

Advantages of using JSX in React

  1. JSX is very simple to understand and think about than JavaScript functions.
  2. Mark-up of JSX would be more familiar to non-programmers.
  3. Using JSX, your mark-up becomes more semantic, organized and significant.

JSX – Acquaintance or understanding

In development region, user interface developer, user experience designer and QA – quality assurance people are not much familiar with any programming language but JSX makes their life easy by providing easy syntax structure which visually similar to HTML structure.

JSX shows a path to indicate and see through your mind’s eye, the structure in a solid and concise way.

JSX – Semantics / structured syntax

Till now, we have seen how JSX syntax is easy to understand and visualize, behind this there is big reason of having semantic syntax structure.

JSX with pleasure converts your JavaScript code into more standard way, which gives clarity to set your semantic syntax and significance component. With the help of JSX syntax you can declare structure of your custom component with information the way you do in HTML syntax and that will do all magic to transform your syntax to JavaScript functions.

React.DOM namespace helps to use all HTML elements with help of ReacJs, is doesn’t it amazing feature? It is. Moreover, the good part is, you can write your own named components with help of React.DOM namespace.

Please check out below HTML simple mark-up and how JSX component helps you to have semantic mark-up.

As you see in above example, we have wrapped <h2>Questions</h2><hr />with <div> tag which has className “divider” so, in React composite component, you can create similar structure and it is as easy as you do your HTML coding with semantic syntax.

<Divider> Questions </Divider>

Composite Component

As we know that, you can create your custom component with JSX mark-up and JSX syntax will transform your component to JavaScript syntax component.

Namespace Components

It’s another feature request which is available in React JSX.

We know that JSX is just an extension of JavaScript syntax and it also provides ability to use namespace so, React is also using JSX namespace pattern rather than XML namespacing. By using, standard JavaScript syntax approach which is object property access,this feature is useful for assigning component directly as <Namespace.Component/> instead of assigning variables to access components which are stored in an object.

JSXTransformer

JSXTransformer is another tool to compile JSX in the browser. While reading a code, browser will read attribute type=”text/jsx” in your mentioned <script> tag and it will only transform those scripts which has mentioned type attribute and then it will execute your script or written function in that file. The code will be executed in same manner the way React-tools executes on the server.

JSXTransformer is deprecating in current version of react, but you can find the current version on any provided CDNs and Bower. As per my opinion, it would be great to use Babel REPL tool to compile JavaScript. It has already adopted by React and broader JavaScript community.

Attribute Expressions

If you can see above example of show/Hide we have used attribute expression for show the message panel and hide it. In react, there is a bit change in writing an attribute value, in JavaScript expression we write attribute in quotes (“”) but we have to provide pair of curly braces ({}).

Boolean Attributes

As in Boolean attribute, there are two values, either it can be “true” or “false” and if we neglect its value in JSX while declaring attribute, it by default takes value as “true”. If we want to have attribute value “false” then we have to use an attribute expression. This scenario can come regularly when we use HTML form elements, for example “disabled” attribute, “required” attribute, “checked” attribute and “readOnly” attribute.

In bootstrap example aria-haspopup=”true”aria-expanded=”true”

JavaScript Expressions

As seen in above example, you can embed JavaScript expressions in JSX using syntax that will be accustomed to any handlebars user, for example style = { displayStyle } allocates the value of the JavaScript variable displayStyle to the element’s style attribute.

Styles

Same as expression, you can set styles by assigning an ordinary JavaScript object to the style attribute. How interesting, if someone tells you, not to write CSS syntax but you can write JavaScript code to achieve the same, no extra efforts. Isn’t it superb stuff? Yes, it is.

Events

There is a set of event handlers that you can bind in a way that should look much acquainted to anybody who knows HTML.

Generally, as per our practice we set properties on to the object which is anti-pattern in JSX attribute standard.

As shown in above example, you can see the anti-pattern and it’s not the best practice. If you don’t know about properties of JSX attributes then propTypes won’t be set and it will throw errors which would be difficult for you to trace.

Props is very sensitive part of attribute so, you should not change it, as each props is having predefined method and you should use it as it is meant for, like we use other JavaScript methods or HTML tags. This doesn’t mean that it is impossible to change Props, it is possible but it is against standard defined by React. Even in React, it will throw error.

Spread Attributes

Let’s check out JSX feature – “spread attributes”:

As you see in above example, your properties which you have declared have become part of your component’s props as well.

Reusability of attributes is also possible here and you can also map it with other attributes. But you have to be very careful in ordering your attributes while you declare it, as it will override the previous declared attribute with lastly declared one.

Props and state

React components translate your raw data into Rich HTML, the props and state together build with that raw data to keep your UI consistent.

Ok, let’s identify what exactly it is:

  1. Props and state are both plain JS objects.
  2. It triggers with a render update.
  3. React manage the component state by calling setState(data,callback). This method will merge data into this .state, and re-renders the component to keep our UI up -to -date. For example, the state of the drop-down menu (visible or hidden).
  4. React component props – short for “properties” that don’t change over time. For example, drop-down menu items. Sometimes components only take some data with this .props method and render it, which makes your component stateless.
  5. Using props and state together helps you to make an interactive app.

Component lifecycle methods

In React each component has its own specific callback function. These callback’s functions play an important role when we are thinking about DOM manipulation or integrating other plugins in React (jQuery).

React Component Lifecycle

ReactJS

Let’s look at some commonly used methods in the lifecycle of a component:

  • getInitialState(): This method will help you to get the initial state of a component.
  • componentDidMount: This method is called automatically when a component is rendered or mounted for the first time in DOM. Integrate JavaScript frameworks, we’ll use this method to perform operations like setTimeout or setInterval, or send AJAX requests.componentWillReceiveProps: This method will be used to receive a new props.
  • componentWillUnmount: This method is invoked before component is unmounted from DOM. Cleanup the DOM memory elements which are mounted in componentDidMount method.
  • componentWillUpdate: This method invoked before updating a new props and state.
  • componentDidUpdate: It is invoked immediately when the component has been updated in DOM

What is Redux?

As we know, in SPAs (single page applications) when we have to contract with state and time, it would be difficult to handgrip state over time. Here, Redux helps a lot, how? Because, in JavaScript application, Redux is handling two states: one is Data state and another is UI state and it’s standard option for SPAs (single page applications). Moreover, bearing in mind, Redux can be used with AngularJs or Jquery or React JavaScript libraries or frameworks.

Now we know, what does Redux mean? In short – Redux is a helping hand to play with states while developing JavaScript applications.

We have seen in our previous examples like, the data flows in one direction only from parent level to child level and it is known as “unidirectional data flow”. React has same flow direction from data to components so in this case it would be very difficult for proper communication of two components in React.

If you compare Redux’s Architecture to other frameworks, it has more benefits:

  • It might not have any other way effects.
  • As we know, binning is not needed because components cant not interact directly.
  • States are managed globally so less possibility of mismanagement.
  • Sometimes, for middleware it would be difficult to manage other way effects.

React Top Level API

When we are talking about React API, it’s the starting step to get into React library. Different usage of React will provide different output like using React script tag will make top-level APIs available on the React global, using ES6 with npm will allow us to write import React from ‘react’ and using ES5 with npm will allow us to write var React = require(‘react’), so there are multiple ways to intialize the React with different features.

Mount / Unmount component

Always, it’s recommended to have custom wrapper API in your API, suppose we have single root or more than one root and it will be deleted at some period, so you will not lose it. Facebook is also having the similar set up which automatically calls

unmountComponentAtNode

I also suggest not to call ReactDOM.render() every time but ideal way is to write or use it through library so, by that way Application will have mounting and unmounting  to manage it.

Creating custom wrapper will help you to manage configuration at one place like internationalization, routers, user data and it would be very painful to set up all configuration every time at different places.

If you like this article and want to learn more in depth with examples Click here

Keep sharing and Enjoy the learning !!!

Harmeet Singh

Leave a Reply

Your email address will not be published. Required fields are marked *