ReactJS is one of the most modern and powerful javascript libraries for building user interfaces. It was initially developed and maintained by Facebook.

In this article, we’ll see how to start with ReactJS using the minimal setup (no use of nodejs). We’ll also talk about each major parts of the library and finally, we’ll focus on existing ReactJS available components in the market.

Quick start with ReactJS

In this section, we’ll show you how to setup your rig to work with ReactJS.

Choose the text editor

In this tutorial, we’re going to use Atom text editor. It is a tool that you can download and use for free (https://atom.io/) . It has a lot of very interesting plugins that may help in your coding experience and most of all it is a multi-platform software.

Once installed, we need to add ReactJS plugins in order to get the most of it. The figure below shows the top 5 React plugins.

We’ll install “react 0.16.2” which is the most downloaded package and certainly the best one.

Writing your first ReactJS program

The particularity of this tutorial is that you’ll work with the minimal required setup. Unlike almost all ReactJS tutorials you may read over the world web, we’re not going to use any additional tools like
node package manager or something like APM, instead, we’ll use CDN. CDN are public remote repositories that you can reference directly in your web page.

1- Create your working directory and add the following two files:

– index.html : a classical html page

– script.jsx : a file with .jsx extension, we’ll see the main line of that later on

2- Open the file index.html with your web browser. For the sake and the simplicity, we use Mozilla Firefox web browser (see Troubleshot below).

Troubleshot:

If you’re using Google Chrome web browser you may encounter this error message [XMLHttpRequest cannot load file:///C:/Log/jsr/script.jsx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.]

Please read the following thread :

http://stackoverflow.com/questions/20041656/xmlhttprequest-cannot-load-file-cross-origin-requests-are-only-supported-for-ht

For that reason, we only use Mozilla Firefox web browser along this tutorial.

Congratulations! You just run your first ReactJs app. Let see how does it work under the hood.

*index.html

It is just like any HTML documents.

The HTML part is easy to understand, we always have a couple of script imports and the main line importing EditorFor.jsx file.

ReactJS props

“Props” are properties that we pass to the component. For example, in the previous example, the label of the EditorFor component can be dynamically managed by the following declaration :

ReactDOM.render(<EditorFor MyLabel=”Name”/>,document.getElementById(“mydiv”));

We can then access the MyLabel props with the syntax {this.props.MyLabel}

var EditorFor = React.createClass({
  render:function(){
    return (





























&lt;div&gt;
      &lt;label&gt;{this.props.MyLabel}&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text"/&gt;
      &lt;/div&gt;





























    );
  }
});
ReactDOM.render(&lt;EditorFor MyLabel="Name"/&gt;,document.getElementById("mydiv"));

We can add as many as props we need and this.props object contains all those available properties inside the ReactsJS component.

In order to do the data binding, we must enclose the property call with curly brackets { }, it tells ReactJS to replace this pattern to the actual prop’s value during the rendering time.

Note: Instead of using declarative component <EditorFor /> markup, you can use the method React.createElement to instantiate the component

ReactDOM.render(React.createElement(EditorFor,{ MyLabel:"Name"}),document.getElementById("mydiv"))

The createElement method takes the component name as it’s first argument and a list of props as it’s second arguments.

Props initialization

The method getDefaultProps is where you should initialize React’s component props. It is always a best practice to give a default value for each props and a well-initialized props guarantees that your component is free on unexpected behavior.

The following codes show how to do that:

var EditorFor = React.createClass({
  getDefaultProps:function(){
    return {
      MyLabel:"Default Name",
      //Enumerate here the list of props
    }
  },
  render:function(){
    return (



























&lt;div&gt;
      &lt;label&gt;{this.props.MyLabel}&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text"/&gt;
      &lt;/div&gt;



























    );
  }
});
ReactDOM.render(React.createElement(EditorFor),document.getElementById("mydiv"))

If you don’t provide any value to your props, the component is going to initialize itself by calling the method getDefaultProps.

ReactsJS Props types

React has some built-in type checking abilities by using the component propTypes objects.

PropTypes helps to keep a strongly typed object in JS. We can tell that a props object is a string or a number by React.PropTypes.string or React.PropTypes.number. Other types are available for more complex data structure: React.PropTypes.array, React.PropTypes.object, React.PropTypes.symbol. PropTypes can be a virtual dom object , in this case we use React.PropTypes.node, React.PropTypes.element

Proptypes also checks data validation by using validator types (React.PropTypes.any.isRequired), you can even define a customized propType.

As stated in the official documentation, for performance reasons propTypes is only checked in development mode.

In the following example, we set the type of EditorFor’s MyLabel props to string.

EditorFor.propTypes={
  MyLabel:React.PropTypes.string
}

React reusable components

An instance of React.createClass is actually an independent component that you can plug into your webpage. You can create as many as you need, each component has it’s own props, behavior and state. If you’re familiar with user controls (.ascx) in Microsoft Asp.net, React components are exactly the same.

React Native

React Native is another version of ReactJS that let you build indistinguishable mobile app from an app built using Java or Objective C.

You can build your native app with only Javascript and React. In addition to that, you can even mix Native Java or Objective-C code with React Native.

One of the big advantages is that React Native uses the same design as React, so don’t worry about your learning curve, once you learn React, you’ll use it everywhere.

React nested component

A component can be used inside another one, we call that a nested component.

The following code shows a nested component.A parent container named FieldSetFor contains two EditorFor components and initializes the MyLabel props.

The two nested components are independent each from other.

var EditorFor = React.createClass({
  getDefaultProps:function(){
    return {
      MyLabel:"Default Name",
      //Enumerate here the list of props
    }
  },
  render:function(){
    return (



























&lt;div&gt;
      &lt;label&gt;{this.props.MyLabel}&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text"/&gt;
      &lt;/div&gt;



























    );
  }
});
var FieldSetFor =React.createClass({
  render:function(){
    return(   



























&lt;fieldset&gt;

&lt;legend&gt;{this.props.legend}&lt;/legend&gt;



























      &lt;EditorFor MyLabel="FirstName" &gt;&lt;/EditorFor&gt;
      &lt;EditorFor MyLabel="LastName" &gt;&lt;/EditorFor&gt;
    &lt;/fieldset&gt;



























  )
  }
});
ReactDOM.render(&lt;FieldSetFor legend="Personal information"/&gt;,document.getElementById("mydiv") )

Adding a “state” to ReactJS component

“State” reflects the component behavior at one point in time. State can change at any time along the component lives. A good candidate for state may be the value of a text input (for example text in search bar).

Unlike props objects, a React component can modify the state value. State is mutable while Props is immutable.

Note: The only place where props values are update is during the initialization.

In the program below, we define two initial states using the special function getInitialState – not mandatory but it’s better to use it.

– textstate =””

– chkstate =”false”

Each time the text value is changed we update each component’s states. when the typed value length is greater than 8 then the component automatically updates it’s internal state and reflects the changes in the UI by checking the checkbox or unchecking it.

We also add onChange event to the input text and bind it to the syncstate method by using {this.syncstate} syntax.

The syncstate private method is in charge of :

– getting the actual value (e.target.value)

– set the new state value with this.setState method and update the label text. You noticed that this state is linked to the label text.

– do some logic rules based on the length of the textState length

var StateSample = React.createClass({
  getInitialState:function(){
    return {
      textstate:"",
      chkstate:""
    }
  },
  syncstate:function(e){
    this.setState({ textstate: e.target.value})
    if (this.state.textstate.length &gt; 8){
      this.setState({chkstate : "checked"})
    }else{
      this.setState({chkstate : ""})
    }
  },
  render:function(){
    return (      





























&lt;div&gt;
      &lt;label&gt;Search text&lt;/label&gt;
      &lt;input type="text" placeholder="enter a text" onChange={this.syncstate}/&gt;
      Long text &lt;input type="checkbox" checked={this.state.chkstate} &gt;&lt;/input&gt;
      
        You typed:&lt;label&gt;{this.state.textstate}&lt;/label&gt;
      &lt;/div&gt;





























    );
  }
});
ReactDOM.render(React.createElement(StateSample),document.getElementById("mydiv") )

We’ve seen so far that props and state are two ways to pass parameters from outside to the React component. They are not actually doing the same thing. You may wonder yourself which one to choose in a specific case. There are some ideas that may help you to choose the best one:

-You can picture props as something immutable in the same way as configuration parameters of the component. Props should be managed by the outside and passed to the component. The component cannot change its props.

-State are something mutable, the component should manage the state change internally (never from the outside). State are private and only accessible by the component itself.

– They both can be initialized from parent component

– Only props can be changed by parent component

– They both can set default values inside component. If values are received from parents then default values are override

– Only state can be changed inside a component, props doesn’t

– The both can set initial values for Child components

– Only props can change in child component.

When changes occurs in Props or in State , the component automatically triggers the render method. In the previous example, that was exactly what happened: we’ve only update the state and ReactJS automatically updates the UI with the fresh value of state.

React stateless function components / React stateful function components

A component is stateless when it has only props, no state.

A stateful has both props and state ( also called state managers).

React Component lifecycle

The creation of a react component follows the next sequence :

– call of the built-in getDefaultProps method, you can redefine it if needed

– call of the built-in getInitialState method

– call of the built-in componentWillMount method before the render step

– call of the user-defined render method

– call of the built-in/redefined componentDidMount method. If you need to get data or update states, componentDidMount method is the right place to do those stuffs.

Note : If a state change occurs, the component invokes the render method to update the UI. This is even possible if you’re updating the state in async mode (for example using setTimeout function)

You can add the following componentDidMount method to the previous code, the chkstate is updated async 3 seconds after component loads and UI is refreshed after that interval.

componentDidMount:function(){
  var self = this;
  setTimeout(function(){
    self.setState({chkstate:"checked"});
  },3000);
}

Material UI React

Material UI is a graphical design specification suggested by Google. It states a set of design principles defining the UI design.

A complete detail is available at https://material.io/guidelines/

React Toolbox is a full set of ReactJS components and CSS modules that fill out Material UI specifications. It contains a lot of ready made Reacts basic controls like input, button, radio button,… and also provides advanced controls like tables, time_picker, progress bar…

The project is available on GitHub at https://github.com/react-toolbox/

Testing react components

Developers can do unit tests against their React components. There’s two things that you have to be acquainted in React testing: the testing library and the testing framework. The most popular test utilities in React is the package ReactTestUtils. The official page is available here . The testing framework runs generally on the server side using nodeJS. Facebook uses Jtest for Javascript testing.

The enzyme, a testing framework powered by Airbnb is also a very useful tool because it offers assert methods capabilities.

For example, you can test component events results, the behavior or the render output against an expected value.

In the majority of cases, those tests are fired at the server side.

You can also combine ReactJS and Redux to test your components. Redux architecture splits component’s parts into 4 layers :

-views, actions, dispatcher, and stores. You can mock data on each layer.

React and bootstrap

React-Bootstrap is a very promising front-end framework for building responsive app with React and Bootstrap.

The framework uses two main components which are :

bootstrap stylesheet

– bootstrap javascript named react-bootstrap.js contains all components

Those files are available on CDN making the use very easy. You just need to reference those CDN links and everything should be fine, you don’t need to install nodeJS to initialize your web app project in this case. According to the road map, all existing component in the classical version of bootstrap will be also available in react-bootstrap.

The project is available at https://react-bootstrap.github.io/ and is under active development at the time of writing.

Improving your development experience

Facebook offers a great tool to debug your ReactJS program. It is provided as a web browser plugin named “React Developer Tools”.

Since ReactJS dynamically adds HTML final outputs to the DOM, React Developer Tools allows us to revert back to the props and state objects and inspect their actual values.

It is available on most commonly used IDE and browsers as Chrome, Firefox, Atom, Nuclide and Electron. The standalone app is coming soon according to the official project’s GitHub page (https://github.com/facebook/react-devtools)

ES5, ES6 (ES2015), …

You will often see those terms when you’re reading ReactJS. They are referring to different ECMAScript version. ECMAScript is the specification of Javascript language and is implemented in all browser Javascript engines.

ES6 brought a lot of new features like arrow functions which are intensely used in ReactJS program. You may not be familiar to them because they are very recent. It may be confusing at the first time but after all, you can always keep your actual style of writing JS program because the difference is essentially at the syntactic level.

React and Angular

ReactJS is designed to manage the view in the MVC paradigm while Angular has a complete architecture to manage all three layers of MVC pattern.

However, Facebook’s engineer designed Flux, an architecture that aims to fulfill the MVC pattern.

Flux has four major components:

Views : view manages the render in the DOM, handles user events and triggers actions

Actions and Dispatcher : in MVC architecture, they are the controller C

Stores : contains data, acts as the Model in MVC pattern.

The GitHub fork is available here

React and URL Routing

URL Routing is an abstraction of the physical resource location into a logical resource.

Web sites use URL Routings to improve their SEO. Instead of directly exposing physical file (/index.html), URL Routing can make it more user-friendly readable like /Product-Discount. React-Router is a module that maps React Component to path.

React and Webpack

As the name implies, Webpack is the combination of two words Web and Pack. It acts as a bundler module that serves static components (css/js) into grouped packages.

Actually, it is more than that. Webpack is running at the server side (nodeJS). You can define configuration rule of how contents should be served to the client.

For example, you can tell it to combine a set of js files into one package and serves your css files together in one another package. Thus it allows to reduce incoming and out coming requests

to your server. Since ReactJS app may use a lot of modules, Webpack can improve the maintainability of your web app.

The official website is at http://webpack.github.io/docs/tutorials/getting-started/

React best practices

We share here some developers feedbacks and best practices

– keep your component small. The official “Think in react” article states that it is always

a good idea to make unitary component, never overload the component in functionalities split it to several smaller components instead. It is extremely easy to read and to maintain modular component.

avoid the use of state as possible as you can. Using a lot of state in your component will be an earlier source of confusing. State is used for interactivity so values can change many times. State also make component testing complicated. Sharing state with an upper component in the hierarchy becomes tricky, instead of using props is a better way to do that.

-Since ReactJS managed only the view, it’s a very big mistake to try to overload your component with data gathering calls or action invoking stuffs. A better workaround is to use Redux.js. As we’ve stated in this article, Redux.js provides a full MVC architecture to your React app.

-always use propTypes for the safety of the component. propTypes are able to check

that your props are in the correct data types. They are also data validator utilities. Remember that propTypes are only available during the development stage.

ReactJs is also suitable for UI TDD (Test driven development). You can build your component with minimal knowledge and test it to check that it satisfied the minimal requirements. When you get more complex details about the final UI component, you just add those specifications to the actually tested version and redo the test again.You repeat this process till the whole functionality are implemented.

-ReactJs is evolving quickly and a lot of third party frameworks come into the market .

Be sure you stay tuned with the latest news about them.

ReactJS & Babel

This is a frequent word that you’ll see every time. Babel is a javascript compiler and the official website is at babeljs.io.

Under the hood, Babel only transforms javascript syntax. For example, it takes as input a JSX file and gets native javascript out. But it is more than that. Babel has many different plugins

that allow you to transform many other formats even write your own transform rules. One

reason to use Babel is that some old vendor web browsers aren’t compliant with new

ECMAScript features. Babel is in charge of transforming those latest features to be compatible

with the former ECMAScript specifications.

A command line interface CLI (Babel-CLI) is also available to allow interactive program and you can even attach your program to the debugger engine.

One of the advantages of babel engine is that it has a full support of the latest version

ECMAScript ( it especially supports arrow functions syntax that are commonly used by many
developers ) A Babel program can run both at the server side (nodejs) or client side(web browser). Some developers tell that Babel is more efficient than JSXTransformers.

ReactJS and Node package manager

Npm as Node package manager is a utility that takes care of components dependencies and the versioning. If you are a beginner with that, you may wonder yourself the relationship between them. They are actually independent each from other. You can return ReactJS component without using Node package manager. Our first example shows that we didn’t use Npm, instead we directly use CDN resources.

This is true while your app is pretty simple but when it grows up it becomes extremely hard to work without node package manager. The reason is that most of ReactJS component use a lot of dependencies and npm is the best way to automatically resolve those dependencies with safety.

ReactJS and asp.net

If you are an asp.net developer, ReactJS.net is definitely complete tools to use ReactJS with your asp.net MVC project.

It is even the best place to start if you’re a pure C# asp.net developer and want to discover the ReactJS world.

One of the big advantages is that it is a cross-platform oriented framework allowing you to go for a classical asp.net MVC project or .net core MVC project. It is available on Nuget package manager via React.Web.MVC4 package for .NET Framework and React.AspNet for .NET Core.

The framework allows JSX server-side rendering (at the writing, they stated it as a super fast process) and offers a lot of MVC Razor Helpers like @Html.React*. For more details about this project, you can visit the project’s fork is at

https://github.com/reactjs/React.NET

ReactJS inline styles

This is also a frequent term in ReactJS world. Inline styles allow you to declare CSS style through a variable into you js or JSX files.

render:function(){
  var labelStyle = {
    color:'red'
  }
  return (




























&lt;div&gt;
    &lt;label style={labelStyle}&gt;{this.props.MyLabel}&lt;/label&gt;
    &lt;input type="text" placeholder="enter a text"/&gt;
    &lt;/div&gt;




























  );
}
});

We declare an inline style named labelStyle , it looks like a common css declaration with respecting that the key name should be in camel case version (for example backgroundImage instead of background-image, I is capitalized) We then assign the labelStyle to the label tag.

The previous example also shows you how can you deal with CSS in ReactJS.of course you can always use the old fashioned way of declaring css separately in the .css file. The advantage here is that we can dynamically change CSS property value.

ReactJS and Browserify

Most node modules require dependencies, those dependencies are declared in each js file with the keyword “require”.

This keyword is used by Node.js on the server side. Based on the required dependency, Nodejs engine resolves them by pre-loading those file before working the current file. Unfortunately for us, your browsers don’t know that NodeJS method and an error is thrown when we try to make directly link to any js files in the node_modules folder.

Here comes the utility of Browserify. The principle is to start with one unique js file and tries to recursively bundle all dependencies into one big file. The bundle file is then rendered to the client. It is also better to minify the bundle js file to reduce the http response size.

Other alternatives that are interesting are uglify, gulpjs, grunt.

Conclusion

We’ve covered along this tutorial a global view over ReactJS universe. There are a lot of existing tools and frameworks and there’s also a lot of incoming new tools in the nearest future. Some of them happen in the View layer, some others are done at the server side for example with NodeJS. We all know that it is a bit hard to have a full control on all of them, especially that some of them have a very good support and have a very active community. You should go for the one that is well supported. The best choice depends on your need and on your skill.

Before you decide to adopt definitely ReactJS as your main rendering framework, the following link is very helpful https://facebook.github.io/react/.