React or Vue? Choosing a library for front-end development

Original author: Juan Vega
  • Transfer
What to do frontend? The surest way to find the answer is to try the best libraries on your own. Ideally, it would be nice to start with the simplest and understand how mysterious for the uninitiated design turn into pages ready for output. Further, armed with an understanding of the basics, you can meaningfully read the documentation and complicate your own experiments until the answer seems obvious. Today we'll talk about React.js and Vue.js. These are some of the most popular JavaScript libraries in the world. Take a look at this



list, see their repositories on GitHub. Both have impressive capabilities and are used to create user interfaces. Working with them is quite simple, the main thing is to immediately understand what's what, take the right first step. As a matter of fact, this material is dedicated to this first step in development using React and Vue.

At first glance, these libraries are very similar. Indeed, they serve the same purpose. The similarities are not limited to this. In particular, the documentation for Vue.js has a section dedicated to comparing with other frameworks. A special place, precisely because of many common features, is occupied in it by comparison with React. However, we are more interested in the differences, moreover, regarding the practical aspects of the work. Namely, we are talking about how the user interface of the application is described using these libraries.

Let us quote the Vue documentation, which, incidentally, was prepared with the participation of the React community: “In React, all components describe their UI using render functions using JSX, a declarative XML-like syntax that works inside JavaScript.” In fact, we are talking about that React mechanisms help embed HTML markup directly into JavaScript code. In Vue, basically, a different approach is taken. It uses templates that are located in HTML files, and are similar to regular HTML markup. At the same time, JSX descriptions do not reach web pages.

In order to understand the basics of React and Vue, consider the solution to a simple task of listing a page. First, a few words about how this is done, so to speak, manually.

HTML and nothing more


Our task is to display on the web page (add to the DOM) a list of names of recently employed employees of a certain company.

If you do this using exclusively HTML, you first need to create a regular HTML file (let's call it index.html), in which, in addition to service tags, there will be such a construction:

     
  • John
  •  
  • Sarah
  •  
  • Kevin
  •  
  • Alice

There is nothing remarkable here; this is a regular HTML list. As long as there are only a few elements in it, manual editing of the labor code will not be. But what if we are talking about a list of several hundred or thousand elements, without even considering that such a list may need, for example, a dynamic update? Without specialized tools, such as React and Vue, dealing with this amount of data is very difficult.

Now let's take a look at how to solve the same problem with React.

React JSX


So, we display the list by means of React.

The first step is to create another index.html file. But in it, instead of the tags forming the list, we will add an ordinary element div. It will serve as a container into which what will be generated by React will be displayed.

This element must be unique IDso that React can find it and work with it. On Facebook (if anyone doesn’t know - React comes from there), the identifier of these elements is usually the keyword “root”, so we will do the same.


We pass to the most important. Create a JavaScript file that will contain all the React code. Let's call it app.js. We will write in it that will allow listing the new employees in the DOM using JSX.

First you need to create an array with the names of employees.

const names = [‘John’, ‘Sarah’, ‘Kevin’, ‘Alice’];

Now you need to create a React element that dynamically displays the entire list of names. There is no need to manually write code to display each of them.

const displayNewHires = (
  
       {names.map(name =>
  • {name}
  • )}  
);

The most important thing to pay attention to is that you do not need to create individual elements yourself
  • . Enough to describe how they should look, a React will do the rest. This is a very powerful mechanism, which is great for solving the aforementioned “thousands of list” problem. With the increase in data volume, the advantages of React over manual typesetting become quite obvious. Especially if the elements
  • more complex than the ones we used here. The last piece of code that is needed to display data on the screen is a function ReactDom.render.

    ReactDOM.render(
      displayNewHires,
      document.getElementById(‘root’)
    );

    Here we tell React that we need to output the contents displayNewHiresto an element divwith an identifier root.

    const names = [‘John’, ‘Sarah’, ‘Kevin’, ‘Alice’];
    const displayNewHires = (
      
         {names.map(name =>
    • {name}
    • )}  
    ); ReactDOM.render(  displayNewHires,  document.getElementById(‘root’) );

    Here it is important not to forget that before us is the React code. That is, before execution, all this will be compiled into ordinary JavaScript.

     ‘use strict’;
    var names = [‘John’, ‘Sarah’, ‘Kevin’, ‘Alice’];
    var displayNewHires = React.createElement(
      ‘ul’,
      null,
      names.map(function (name) {
        return React.createElement(
          ‘li’,
          null,
          name
        );
      })
    );
    ReactDOM.render(displayNewHires, document.getElementById(‘root’));

    That, in fact, is all. The result is a React application that displays a list of employee names from an array. Nothing special, but this simple example should give you an idea of ​​what React can do. And how to do the same with Vue?

    Vue Templates


    Here, as last time, we will write an application that allows you to create a web page with a list of names.

    Create another index.html. Inside the file, place an empty element divwith an identifier root. It is worth noting that the identifier of the element can be assigned as you like, it does not play a special role. The main thing is that this IDmatches the one that will be used in the code.

    The element divwill play the same role as in the React application. It will tell the JS library, this time Vue, which part of the DOM to access when the output to the page begins.

    Once the HTML file is ready, it's time to create a JavaScript file that will contain the Vue code. Let's call it, as before, app.js.

    Now it's time to talk about exactly how Vue displays data on pages.

    Vue, when it comes to DOM manipulation, uses a template approach. This means that the element in the HTML file divwill not be completely empty, as was the case with React. In fact, a large part of the code will be rendered into the HTML file.

    To better understand this, let's recall how to create a list of names using regular HTML.

    The list is represented by a tag.
      containing a number of elements
    • . In Vue, you need to do almost the same, but with some changes. So, create an element
        .


          Now, inside this element, create one empty
        • .

             
          •  

          So far, everything is quite familiar. Edit
        • by adding a Vue directive to it that looks like an attribute of a tag.

             
          •  

          Native directives are an approach that Vue uses to add JavaScript functionality directly to HTML. Symbols are located at the beginning of directives v-, followed by a descriptive name that allows them to understand the roles of directives. In this case, we have a cycle for. For each name of listOfNameswe want to copy an element
        • and replace it with a new element
        • containing this name.

          Now, in order to make the code workable, only a little remains. Namely, what has already been written will allow the formation of an element
        • for each name on the list. But we have not yet informed the system that this element should contain a name from the list. In order to fix this, you need to add to the element
        • A design whose syntax is similar to Mustache templates. You may already have seen this in other JS libraries.

             
          •    {{name}}  

          Element
        • ready for work. Now each of the elements of the list formed by the Vue tools will output the name from listOfNames. It is worth remembering that the word "name" in this case is chosen arbitrarily. With the same success, you can use any other, say, “item”. All that the keyword does is serve as a substitution field that will be used when processing the list of names.

          It remains only to create a dataset and initialize Vue in the application. To do this, create a new instance of Vue. Assign it to a variable app.

          let app = new Vue({
          });

          The Vue object accepts several parameters. The first, and perhaps the most important, is el(that is, an element). He tells Vue where exactly in the DOM is where you need to add new elements. This is very similar to how React works.

          let app = new Vue({
            el:’#root’,
          });

          The final step is to add data to the Vue application. In this library, data is transferred to the application through the Vue instance parameter. In addition, each Vue instance can have only one parameter of each kind. Although there are a lot of parameters, in our example we can focus on only two - this is the above el, and the parameter data.

          let app = new Vue({
            el:’#root’,
            data: {
              listOfNames: [‘Kevin’, ‘John’, ‘Sarah’, ‘Alice’]
            }
          });

          The object datanow contains an array listOfNames. And when you need to use this data set in the application, you only need to call it using the directive. It's pretty simple. Here's what the finished application looks like.

          HTML:

           
               
          •      {{name}}    
          •  

          JavaScript:

          new Vue({
            el:"#root",
            data: {
              listOfNames: [‘Kevin’, ‘John’, ‘Sarah’, ‘Alice’]
            }
          });

          Conclusion


          Now you know how to create simple applications using React and Vue. We hope you, with the help of our simple examples, have taken the first steps in the development areas using React and Vue, and are ready to move on in search of "your" front-end library.

          In the end, I want to say that both libraries offer an excellent set of features. Usually, although this is probably a matter of habit, Vue is somewhat easier to use. It is worth noting that Vue supports JSX, but a similar approach to creating Vue applications is used infrequently.

          In any case, both React and Vue are powerful tools, any of which allows you to create great web applications, and no matter what you choose, you won’t lose.

          Dear readers! And what do you use for front-end development?

    • Also popular now: