React is a JavaScript library developed by Facebook that is maintained by an ever-growing community. Because of the ability to render React Views both on the client and on the server, the framework is very popular among many developers. So, in this article, I will tell you some basic information about the work of ReactJS.
Although other frameworks have already followed the path of isomorphic rendering (client/server), ReactJS differs from them in one fundamental function: the virtual Document Object Model (DOM). The views do not modify the DOM of the browser directly, but hold it virtually in the components and are thus completely detached from any dependencies. Methods such as renderToString (<React View Component>) can be used to render the React View components on the server.
Some large companies have already shown that React works: Not only parts of Facebook were developed with it, but platforms such as Instagram and the web version of WhatsApp also use the framework. Search Engine Optimization, or SEO for short, is a knockout criterion, especially for pages that are supposed to play a role in search engines. Therefore it should be noted that the server-side rendering of web applications developed with frameworks such as AngularJS is very time-consuming. For example, creating snapshots of the HTML code with PhantomJS is not exactly easy for dynamic pages – and also not particularly efficient.
In React, on the other hand, all components create their own virtual DOM. This not only allows them to be rendered on the server but also makes unit testing easier. If components change, for example, due to user interactions or new responses from the server, the virtual DOM does not attempt to re-render the entire application, but only the smallest affected element.
An example can explain the performance gain more clarity. Assume there is a model (see Model View Controller) that is supposed to depict an office building, for example. All relevant properties of the building (rooms, windows …) are mirrored to the current state of the object. React exhibits such behavior with the DOM.
If several rooms in the building are merged in favor of an open-plan office, the framework would deal with it as follows: First, it identifies all changes that are taking place (reconciliation), and then it updates the DOM accordingly. It is important that React would not build a new building, but only redesign the affected rooms. If a DOM element is changed but its parent element is not, the latter is not affected.
Install ReactJS
The React Starter Kit is available as a download or as a JSFiddle Snipped to get started right away. On the client side, it is sufficient to include the react.js file. JSXTransformer.js can also be added as an option in order to be able to parse the components written in JavaScript XML (JSX) (more on this later). React code can then be developed in a script block with type = “text / js”:
<!DOCTYPE html> <html> <head> <script src="build/react.js"></script> <script src="build/JSXTransformer.js"></script> </head> <body> <div id="example"></div> <script type="text/jsx"> React.render( <h1>Hello, world!</h1>, document.getElementById('example') ); </script> </body> </html>
The JSX code is not in the website code, but is stored in a separate file, compiled with tools such as Webpack or Browserify and integrated once.
If Webpack and the associated npm module jsx-loader are installed, the following file webpack.config.js is sufficient to get started right away:
'use strict'; var path = require ('path'), targetPath = path.join (__ dirname, 'build', 'assets'), config; config = { resolve: { extensions: ['', '.js', '.jsx'] }, entry: [ './site.jsx' ], output: { path: targetPath, filename: 'bundle.js' }, module: { loaders: [ {test: /\.jsx$/, loader: 'jsx-loader'}, ] } }; module.exports = config; The bundle is to be included before the closing body tag of the HTML page: ... <script type = "text / javascript" src = "build / assets / bundle.js"> </script> </body>
Structure, syntax, and properties
On the front-end side, ReactJS consists of components (views):
React.renderComponent ( React.DOM.h1 (null, 'Hello, world!'), document.getElementById ('example') );
With JSX the whole thing looks similar:
/ ** @jsx React.DOM * / React.renderComponent ( <h1> Hello, world! </h1>, document.getElementById ('example') );
Even if the mixing of JavaScript and HTML seems a bit strange at first glance, the feeling fades after a short time. The separation of the code of the two languages is basically a so-called separation of languages and the merging does not contradict the principle of separation of concerns.
If a component gets too big, it makes sense to split it up into several smaller, reusable components. Ideally, they are so small that they can be easily covered with unit tests and enable a clear and clean structure of the application.
The JavaScript XML Syntax (JSX)
At first glance, React components look just like everyday HTML. This is not the case, however, because it is just an XML-like representation that is supposed to make developing JavaScript renderings more pleasant.
Attribute names such as class are not allowed. The equivalents className and htmlFor, therefore, offer the functions of the HTML original. These and other peculiarities of the syntax can be read in the JSX Gotchas in the project documentation.
Browsers cannot execute the JSX code, which is why it must be transformed into native JavaScript. A before and after example shows the effect:
var AComponent; // Input (JSX): var app = <AComponent text = "Hello" />; // Output (JS): var app = React.createElement (AComponent, {text: "Hello"});
The first ReactJS component
Components can be created with the React.createClass command. You are to be given an object specification which, in addition to many optional methods for the behavior with the render method, contains single mandatory information:
var AComponent = React.createClass ({ render: function () { return ( <h1> Hello, world! </h1> ); } });
Then you can render the method in any DOM element:
React.renderComponent ( <AComponent />, document.getElementById ('example') );
Applications that are made entirely from React will only call this method once for the main component. All remaining components such as header, navigation, footer and content are encapsulated in the main component.
Properties and states in React
In order to incorporate some display logic, the parent component can pass on so-called props (properties). The properties are available in the child components by calling this.props:
var DayComponent = React.createClass ({ render: function () { return ( <h1> Today is {this.props.day}! </h1> ); } }); React.renderComponent ( <DayComponent day = "Sunday" />, document.getElementById ('example') );
While props are immutable and intended for read-only access, state enables interactions. It can be found within the component and can be changed, for example, when you click a button or when a REST service is returned with this.setState (). If the render method also uses the status of the component, it is automatically re-rendered if it changes.
When creating a component, it optionally gets its state with the getInitialState method:
var DayComponent = React.createClass ({ getInitialState: function () { return { day: "Tuesday" } }, render: function () { return ( <h1> {this.state.day} </h1> ) } });
If the application loads data from the server via GET request, it is mirrored in the components. For example, an asynchronous request can be sent to the server with jQuery and, if the return is successful, set directly to the state:
var DayComponent = React.createClass ({ ... getInitialState: function () { return {data: []}; } componentDidMount: function () { $ .get ({ url: this.props.url, dataType: 'json', success: function (data) { this.setState ({data: data}); } .bind (this); }); } ... });
After rendering, ReactJS automatically calls the componentDidMount method. If the application updates the status with this.setState (), the new data from the server replaces the initial data array and bring the component up to date. In addition to componentDidMount, there are other methods that are explained in more detail in the next section.
Actions and Action Creators
In a React app, a large part of the interactions takes place via actions. Action creators are semantic auxiliary methods that send actions to the central dispatcher. They can be executed in the event handlers of the views or in response to a response from the server.
var AppDispatcher = require ('../ dispatcher / AppDispatcher'); var TodoConstants = require ('../ constants / TodoConstants'); var TodoActions = { updateText: function (id, text) { AppDispatcher.dispatch ({ actionType: TodoConstants.TODO_UPDATE_TEXT, id: id, text: text }); } }; module.exports = TodoActions;
Conclusion
While it was hardly conceivable a few years ago to develop a complete application in JavaScript, today many companies are migrating their websites to flexible frameworks such as React. The isomorphic project can be executed on the server and thereby increases the performance in the browser. At the same time, there is a pleasant advantage for search engine-relevant pages, and the possibility of using code on both the client and the server-side saves a lot of development effort.
The virtual DOM also makes unit tests of the application easier, because the generated HTML can be checked by passing state in the individual components.
So, that was it. I hope that this article was a helpful guide for you and now you know more about how ReactJS exactly works. Thank you for being here and good luck on your programming path Hire an expert here: https://www.ava.codes/hire-reactjs-developer!