Full stack Web Development

Pure React

In this blog, we will have a comprehensive discussion about React to understand what is going on behind the scenes. The objective of this blog is to understand how React works internally. We will not introduce JSX. You can use React without pure React.

What is Pure React

To set up the page for the view and rendering your page into a browser, we will be using two libraries: React and ReactDOM. React is the library for creating views. ReactDOM is the library to render UI in the browser.

Note: 
React and ReactDOM were split into two packages from version 0.14. The release notes state: 
“The beauty and the essence of React have nothing to do with browsers or the DOM... This 
[splitting into two packages] paves the way to writing components that can be shared between 
the web version of React and React Native.”

Let’s create an HTML document set up with React. For this, we can use an online code editor called codepen. Add these two links below when you will do the local set for it in codepen editor React and ReactDOM libraries are used to render the UI in the browser.

https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js
https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js

Create a New Pen

HTML document setup with React

Let’s see how to write and reuse HTML in our code and how we can reuse our HTML code.

After adding CSS it as shown below

Let’s copy the same HTML code and create one more card.

If you look closely you are copy pasting the same HTML and writing more codes. Now let us see how to minimize this and reuse the HTML code with react.

You will find this popup when you click on JS setting. Later, two more external libraries will be added from React.

Select in the Quick-add option as React and ReactDOM.

Please select Babel as JavaScript Preprocessor, which is a tool to transpile React code and convert it to browser understandable mode.

We are creating a function with the name Person () which in turn creates a Component. Make sure you write the component name by starting the letter in uppercase. Inside function Person () there is a return statement, that returns HTML code. We want to render this into DOM.

It might look strange to you if you are new to React learning because you are returning HTML code in the JavaScript function. This concept we will cover in the next blog as JSX. Let’s see next step

Now, let us do some changes in the HTML section

We have created an empty div block using id=” per”. You can use any id name if you want.

The React package which we have imported in the JS section is responsible to parse the code to DOM. We have also imported another package called ReactDOM.

The ReactDOM is an Object which contains a render () method. This render () method allows us to render the JavaScript function as a component to the DOM.

As you can see render method accepts function Person in the form of HTML tag and want to render it by document.querySelector(‘#per’). We are trying to render Person component, that returns HTML data to the empty div block.

In the above screenshot, you can see that Person component data got rendered in the empty div block.

Note:  Do Not use a class inside function Component Person. In case you have used it, you will get a warning
 in a console.


Since the class is a reserved word used in React, therefore, we will be using className. More information we can get it in JSX blog.

The person component we have created can display one-person detail because we have hardcoded the person value. But if you want to render more than one personal details we must again hardcode the value. The main advantage of React is we can create Reusable Components. Below we will see how to do it.

We have passed props as a parameter to the Person function. Props are a parameter that dynamically accepts the value whatever that is passed to Person Component. You are passing name and skills for props in line number 13. In line number 6 and 7 you can find how they are accessed.

Now we can render it dynamically for other Person details.

Summary of the above code

As you see we used React Functional Component and dynamically rendering two-person details with reusing the Person Component. This means we no need to hardcode the HTML code again and again for rendering new person detail. React makes User Interface Development easy. Using React we can build better UI.

Conclusion

In the next blog, we will be understanding JSX with doing the local setup. Stay tuned for more updates in React series blogs.

Som

is a full-stack web developer, designer, and educator who has been building user interfaces for over a decade. He’s done work for Fortune 4 companies, national political campaigns, and international technology leaders. His proudest achievement is helping people learn full-Stack web development.

20 Comments

  1. Little bit confusion invocked after going through this article that how to call component’s render method?
    Can you add some more stuff to make this article more meaningful like passing an event handler as a prop

    1. I think you are talking about render lifecycle method. We are not using class component here. We are using functional component. They are different. The render method from ReactDOM is used to inject our component to an HTML page.

  2. Can you give a light on it that how they are differnt,it will be highly helpful for beginner and somewhere you have written below line of code.

    ReactDOM.render(,document.querySelector(“#per”));// please explain this line of code,what is the purpose of writing

    1. When we write ReactDOM.render(,document.querySelector(“#per”)), this will make our React component to be rendered into the HTML. The document.queryselector will look for the element with a parameter passed to function. In this case element with id per. Once it gets the element it will render the React code inside that element.

  3. @sandesh function and class ,both are object in javascript,so what are the main differnces in their usage ???
    BTW your article is very helpful.

    1. Es6 way(using class) has the very cool way to handle prototype and inheritance, get rid of unnecessary crippy steps to inherit something from somewhere
      just observe below the line of code
      // es5 way
      // Person constructor
      function Person(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
      }

      // Greeting
      Person.prototype.greeting = function(){
      return `Hello there ${this.firstName} ${this.lastName}`;
      }

      const person1 = new Person(‘John’, ‘Doe’);

      console.log(person1.greeting());

      // Customer constructor
      function Customer(firstName, lastName, phone, membership) {
      Person.call(this, firstName, lastName);

      this.phone = phone;
      this.membership = membership;
      }

      // Inheriting the Person prototype methods
      Customer.prototype = Object.create(Person.prototype);

      // Make customer.prototype return Customer() ,another unnecessary step
      Customer.prototype.constructor = Customer;

      // Create customer
      const customer1 = new Customer(‘Tom’, ‘Smith’, ‘555-555-5555’, ‘Standard’);

      console.log(customer1);

      // see the Es6 way

      class Person {
      constructor(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
      }

      greeting() {
      return `Hello there ${this.firstName} ${this.lastName}`;
      }
      }

      class Customer extends Person {
      constructor(firstName, lastName, phone, membership) {
      super(firstName, lastName);

      this.phone = phone;
      this.membership = membership;
      }

      static getMembershipCost() {
      return 500;
      }
      }
      const john = new Customer(‘John’, ‘Doe’, ‘555-555-5555’, ‘Standard’);
      console.log(Customer.getMembershipCost());
      #copied
      // Internaly the working mechanism of proto is same ,if you observe the console.

    2. The class keyword was introduced in JavaScript with es6. Before that, we were using the function to create Objects. Using class keyword makes OOP concepts easier in JavaScript.

      1. complte your sandesh @sandesh ,we can say it using the function constructor there is lot of differnce between function constructor and function in Javascript Where is Som Sir??

        1. Hi Shruthi,
          please share your question you are saying something about function constructor and function what clarification you want

          1. Theoretically I have read ,but can you give me the code where I can differentiate between function constructor and function in javascript?
            somewhere I have studied if you dont mention return statement inside function constructor then also we can create objects on the fly?
            what are the scenario where If I want to create same object(same in terms of the property which we are returning ) from the function constructor by skipping or you can say totally avoiding the content of function constructor no matter how many times I called the function constructor?

          2. Well, Function constructor means its an Object Constructor, there are certain Object patterns when you are dealing with javascript as object-based programming language. The design patterns are this way as follows:

            when we write in a functional format as this way

            function People()
            {

            };

            console.dir(people);// You will get function is dervied from function prototype ->constructor method is available->constructor is been dervied from->Object.prototype. Orginally function is also an Object in Javascript.

            Technically we write Object constructor in this way as :-

            var peopleconst=function(name,age,skill)
            {
            this.name=name;
            this.age=age;
            this.skill=skill;
            this.printdetail=function()
            { console.log(“The name is “+this.name+ “age is” +this.age+ ” skill is ” +this.skill);}

            };
            var people=new Peopleconst(“som”,20,”js”); //reuseability of constructor for new instances each time. where as in function we have to rewrite the function again and again.
            people.printdetails();

            Go with Factory pattern concept you will get more.

        1. Please try to get my explanation correct you have asked about Function vs function constructor.
          Go more logical In JavaScript, any function can return a new object. When it’s not a constructor function or class, it’s called a factory function.

          Therefore I asked you to understand what is the factory function pattern

  4. //Explanation
    function helloBuffallo(firstName){
    this.firstName=firstName; /// this is referring to the current instance ,in this context a1
    }
    var a1 = new A(“Shibin MC”); /// a1 object being created

    Question how can we treat the above function constructor as a general function
    so the answer is just call it as usual without new operator and most importantly it will add firstName in global scope.
    scroll to the top and observe function constructor ,I have not writtenn return statement but still i am getting object which I have created using new operator
    do some modification and add return “Teacher should not be cheater”;you will observe nothing will
    happen in the output which we have got earlier ,modify the above return statement and return object with any content ,you will now see the output now differs.

    coming to the function factory,here I I think user do not want to mix the concept of closure to produce differnt function from function factory,it is totally off the topic

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close