• Skip to main content
  • Skip to primary sidebar
BMA

BeMyAficionado

Inspire Affection

ReactJS (ES6) and AJAX to Fetch Data from Servers

March 12, 2017 by varunshrivastava Leave a Comment

Hey developers! I wrote a blog about the best javascript frameworks of 2017 and ReactJS is one of them. ReactJS is one of the best javascript framework to create views. It is developer friendly plus it gives you lot of tools to make your overall experience smooth. ReactJS loves component driven programming. So, if you are not familiar with component based programming then it’s time you start learning it. Component driven programming is the future of future javascript based frameworks. Here’s an article by reactJS team on “Thinking in React”.

Before ES6, we had to write quite some code, but after ES6, we can achieve the same thing with less lines. Also, it gives us the freedom to use class and properties, just in a way we are familiar with. In ReactJS everything is a component. We separate a single module in multiple components. Each component has their own data, properties, methods, view, and state. Components can be nested into each other. Data flow is from the top component to the bottom in the hierarchy.

Table of Contents

  • What you will learn?
  • Setting Up the Enviornment
  • ReactJS
  • Conclusion

What you will learn?

Let’s start with our short tutorial. In this tutorial, we will be fetching the list of categories from www.varunshrivastava.in website. You must have a basic knowledge of javascript and must be fluent with it. At the end of this tutorial you will be able to perform the following things:

  1. Setup ReactJS on your website.
  2. Create and interact with different components.
  3. Fetch JSON data asynchronously from a REST API.
  4. Extract data from the JSON object document and use it in the required way.

Setting Up the Enviornment

We would need a server at the first place to start with this tutorial. This is because we are going to send an ajax request to another domain from our local. And to do that we need a server. It is because web works on the basis of certain principles. Therefore, obeying one of the principle it does not allow access to its resources if it doesn’t find any valid origin. I have enabled CORS in my website which allow access to certainn resources. So, we would need a local server to host our application. There’s nothing to worry about, I have already written a simple article on setting up your local enviornment with XAMPP control panel. Xampp is one of the simplest way to setup your local enviornment. Setup the enviornment and come back quickly to start creating your first AJAX driven application with reactJS.

  • Setting up your local enviornment with XAMPP Control Panel

ReactJS

Welcome back, Let’s start by setting up ReactJS on our website. Simply create a new .html file and paste below content in it.

<html>
  <head>
    <title>ReactJS Tutorial</title>
  </head>
  <body>
    <div class="container" id="app"></div>

    <script type="text/javascript"   src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.min.js"></script>
    <script src="https://unpkg.com/react@latest/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@latest/dist/react-dom.js"></script>
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>

  </body>
</html>

This is all you need to get started with reactJS. Next, we will learn to create components. If you want colors and visual representation then add below link in the head section of html page:

  • <link rel="stylesheet" type="text/css" href="http://www.varunshrivastava.in/wp-content/themes/whitehogan/style.min.css" />

In reactJS components are simply created by extending React.Component class. You inherit all its property which is required by the component. Let’s create a component.

class CategoryBox extends React.Component {
    constructor() {
     super();
    }
}

Congratulation, you have made your first component. But, as you can see, this component is of no use a it does not perform any task. It’s just an empty component. Now, we will add some behavior to it and make is a bit more useful.

class CategoryBox extends React.Component {
    constructor() {
     super();
     this.state = {
      categories: []
     };
    }
    render() {
      return (
      <div className="row">
         <h1>Hello World!</h1>
      </div>
     );
    }
}

ReactDOM.render(
   <CategoryBox />,
   document.getElementById('app')
  );

The render() method is responsible for creating the view for the user. This is where we create our elements which will render on the client’s browser. It contains the structure of the component. It tells the component how to render on client’s screen. In this case, we are simply returning Hello World! String wrapped inside of h1 tag.

Note: render() method must return one and only one root element. In this case, the root element is div.row. At the end, `ReactDOM.render()` method renders the `CategoryBox` component to the browser. Or in other words, it takes `div#app` and replaces it’s content with whatever is inside the render function of that component. Now, we will create our component to render the list of categories and show it to the user.

class CategoryBox extends React.Component {
    constructor() {
     super();
     this.state = {
      categories: []
     };
    }

    componentDidMount() {
     this.fetchCategoryList();
    }

    fetchCategoryList() {
     axios.get("http://www.varunshrivastava.in/wp-json/wp/v2/categories")
      .then((res) => {
       this.setState({categories: res.data.categories});
      });
    }

    render() {
     var category = this.state.categories.map(function(item, index) {
      return (
       <a href={item.slug}>
        <div className="col s6 m4">
         <div className="box-container" key={item.id}>
          <h1>{item.title}</h1>
          <p>{item.description}</p>
          </div>
        </div>
       </a>
       )
     })
     return (
      <div className="row">
       { category }
      </div>
     );
    }
  }



  ReactDOM.render(
   <CategoryBox />,
   document.getElementById('app')
  );

Woah! Let’s break it. There are 4 main lifecycle methods in ReactJS that are fired at different times in a component life. We have got one reactJS lifecycle method here i.e. componentDidMount(), this method is called just after the component has been mounted successfully. In other words, this method is called when react’s virtual dom is ready to be rendered. We are telling component to fire this method as soon as you render on the client’s machine.

From this method we are calling our custom method fetchCategoryList(). This method is going to send a `GET` request to retrieve the resource we need to render on our page. It sends an AJAX request asynchronously and fetches the list of categories for the blog. You can have any url with json document to fetch the result. Once the data has been received, it set’s the state with this data. Yoou must be careful while setting up the state. Use this.setState()?instead of using this.state.categories?because setter method keeps a track of state change and informs the component that view must be rendered again. As soon as the state of the application changes, it tells component to re-render the component. This time component finds the categories data and maps it accordingly.

Conclusion

ReactJS is a cool framework just like facebook. It enables developers to create some of the fantastic websites very quickly. I know it is a bit difficult to grasp the logics at the first time but once you start playing more and more with it, you start to love it even more. If you have any questions or any part that you want more explanation about then please comment below. I would love to answer all your queries.

And as always
Be my aficionado 🙂

Related

Filed Under: Programming Tagged With: ajax, component driven programming, reactJS, reactJS and Ajax, short tutorial

Primary Sidebar

Subscribe to Blog via Email

Do you enjoy the content? Feel free to leave your email with me to receive new content straight to your inbox. I'm an engineer, you can trust me :)

Join 874 other subscribers

Latest Podcasts

Recent Posts

  • Is The Cosmos a Vast Computation?
  • Building Semantic Search for E-commerce Using Product Embeddings and OpenSearch
  • Leader Election with ZooKeeper: Simplifying Distributed Systems Management
  • AWS Serverless Event Driven Data Ingestion from Multiple and Diverse Sources
  • A Step-by-Step Guide to Deploy a Static Website with CloudFront and S3 Using CDK Behind A Custom Domain

Recent Comments

  • Varun Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Vaibhav Shrivastava on Deploy Lambda Function and API Gateway With Terraform
  • Varun Shrivastava on Should Girls Wear Short Clothes?
  • D on Should Girls Wear Short Clothes?
  • disqus_X5PikVsRAg on Basic Calculator Leetcode Problem Using Object-Oriented Programming In Java

Categories

  • Blogging
  • Cooking
  • Fashion
  • Finance & Money
  • Programming
  • Reviews
  • Software Quality Assurance
  • Technology
  • Travelling
  • Tutorials
  • Web Hosting
  • Wordpress N SEO

Archives

  • November 2024
  • September 2024
  • July 2024
  • April 2024
  • February 2024
  • November 2023
  • June 2023
  • May 2023
  • April 2023
  • August 2022
  • May 2022
  • April 2022
  • February 2022
  • January 2022
  • November 2021
  • September 2021
  • August 2021
  • June 2021
  • May 2021
  • April 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • April 2020
  • February 2020
  • December 2019
  • November 2019
  • October 2019
  • August 2019
  • July 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
  • January 2019
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • June 2018
  • May 2018
  • March 2018
  • February 2018
  • January 2018
  • December 2017
  • November 2017
  • October 2017
  • September 2017
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • April 2017
  • March 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
  • October 2016
  • September 2016
  • August 2016
  • July 2016
  • June 2016
  • May 2016

Tags

Affordable Hosting (4) algorithms (4) amazon (3) aoc-2020 (7) believe in yourself (4) best (4) database (4) earn money blogging (5) education (4) elementary sorting algorithms (4) experience (3) fashion (4) finance (6) Financial Freedom (7) food (7) friends (3) goals (5) google (5) india (10) indian cuisine (5) indian education system (4) java (16) life (16) life changing (4) love (4) make money (3) microservices (9) motivation (4) oops (4) podcast (6) poor education system (4) principles of microservices (5) problem-solving (7) programmer (5) programming (28) python (5) reality (3) seo (6) spring (3) success (10) success factor (4) technology (4) top 5 (7) typescript (3) wordpress (7)

Copyright © 2025 · Be My Aficionado · WordPress · Log in

Go to mobile version