For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogWeb DevelopmentMigrating From jQuery to React? Here’s How!

Migrating From jQuery to React? Here’s How!

Published
05th Sep, 2023
Views
view count loader
Read it in
10 Mins
In this article
    Migrating From jQuery to React? Here’s How!

    jQuery isn’t React and React isn’t jQuery:

    We utilize jQuery to directly alter the Document Object Model (DOM) (i.e. add/hide UI components) and to conduct simple AJAX requests. It also calls browser APIs in a cross-browser consistent manner. jQuery created waves when it first emerged! It was a forerunner to JavaScript community packages, propelling client-side development to new heights. For more information, check out usereducer in react. 

    Migrating from jQuery to React? Here’s how!

    The JavaScript ecosystem has evolved and altered dramatically. Initially, most existing frameworks established their own jQuery-like features, and browsers made their APIs more consistent.

    On the other hand, we now approach web development from a fresh perspective. We believe that directly modifying the DOM is not the best development path. Because DOM elements carry a lot of useless data, when the web page is packed with elements, the performance suffers.

    React is distinct in that it is a UI component management library rather than a utility library that wraps browser APIs. When you use React, you must follow a recommended technique (component-oriented structure) for building your user interface and structure your interactions around well-defined lifecycle functions. If you follow the recommended conventions, you will receive optimizations for free, e.g. it reduces the actual DOM changes that occur to maintain the application performant.

    A single component in React encompasses both the functional aspect of the View and the UI itself. That's correct! Your UI elements in React are written in JSX, a syntax extension of HTML. Although it may appear to be counter-intuitive, it turns out to be far more efficient, and you have greater control and maintenance over your code.

    Handling the DOM

    The main distinction between these two is that React operates through the "virtual DOM," whereas jQuery interacts directly with the DOM. The virtual DOM is a memory-based DOM implementation that compares to existing DOM elements and makes the appropriate changes/updates. As a result, performance is substantially faster.

    jQuery is not appropriate for large-scale applications. It results in spaghetti code generation because standard DOM does not allow complex codes either.

    React's component-oriented architecture and virtual DOM implementation make it appropriate for developing large-scale apps.

    Affairs of the State

    Changing the value of a JavaScript variable within a page might be difficult. Assume you have a variable called message in your application that represents a shoutout. You want that message to be shown within a container <div> like this:

    <div id="message">Message goes here</div>

    jQuery:

    Everything is still read from top to bottom in a jQuery approach. You might use the following code to extract the current message first:

    var message = $("#message").html();

    To update the message, you must refer to the <div> once more and insert the new value:

    var message = "New message"; // Normally set by some other logical routine

    $("#message").html(message);

    One disadvantage of this approach is that the message must be set twice: once to extract the value and again to assign a new value to it. In addition, further code is required to insert the message back into the target <div>. This can quickly become a mess, especially if you have another process that may create a new value for the message. In such situation, you'd need to execute $("#message").html(message) once more.

    React.js:

    React.js overcomes this problem by keeping a single instance of a variable in the state of a component. A state object is defined within each React.js component and is initialized in the component's constructor. For example, imagine you want to keep the same message value, and any logical routine that changes it will be reflected in the component's UI. You could have any of the following:

    import React from 'react';

    export default class MessageComponent extends React.Component {

    constructor(props) {
        super(props);
     
        this.state = {
          message: ""
        }
      }
     
      updateMessage(message) {
        this.setState({
          message: message
        });
      }
      render() {
        return (
          <div>
            {this.state.message}
          </div>
        );
      }
    }

    You'll see that you initialised the message in the component's state within the constructor. The component has a method named updateMessage(message), which calls the setState() function of another component to update the value of message. The idea is that whenever setState() is invoked, the component would re-render the UI as called by render(), because render() provides JSX that displays the message via this.state.message with whatever value it now has.

    Handling Events

    The actions taken by the site visitor throughout their interaction with the website (orr webpage) are referred to as events. There might be a variety of events, such as:

    • The user clicks a button.
    • The mouse pointer is moved over an image by the user.
    • The user pressed any key on the keyboard, and so on.

    To handle DOM events using jQuery methods, first obtain a reference to the DOM element(s) using a jQuery selector and then activate the appropriate jQuery event function.

    Example: Handle Button Click Event

    $('#Btn').click(function () {
        alert('Button clicked');
    });
    <input type="button" value="Save" id="Btn" />

    In this case, we first utilise the id selector to obtain a reference to the 'Save' button, and then we use the click method. We've defined the handler function as a callback function that will be called whenever the Save button's click event is triggered.

    Event object

    Every event handler method receives an event object from jQuery. The event object contains critical properties and methods for cross-browser consistency, such as target, pageX, pageY, relatedTarget, and so on.

    React’s SyntheticEvent System:

    An instance of SyntheticEvent, a cross-browser wrapper for the browser's native event, is supplied to an event handler in React. It provides the same interface as the native event in the browser, including stopPropagation() and preventDefault(). You cannot return false in React to disable default behavior. Instead, preveutilizentDefault must be explicitly invoked.

    If you require the underlying browser event for any reason, simply utilise the nativeEvent attribute to obtain it. The synthetic events are distinct from, and do not correspond directly to, the native events of the browser. OnMouseLeave event.nativeEvent, will point to a mouseout event. The specific mapping is not included in the public API and is subject to change at any time. Each SyntheticEvent object has the following properties

    • boolean bubbles
    • boolean cancelable
    • DOMEventTarget currentTarget
    • boolean defaultPrevented
    • number eventPhase
    • boolean isTrusted
    • DOMEvent nativeEvent
    • void preventDefault()
    • boolean isDefaultPrevented()
    • void stopPropagation()
    • boolean isPropagationStopped()
    • void persist()
    • DOMEventTarget target
    • number timeStamp
    • string type

    The SyntheticEvent is aggregated. This implies that the SyntheticEvent object will be reused, and all properties will be negated when the event callback is called. This behavior is intended to improve performance. As a result, a SyntheticEvent cannot be used asynchronously. By clicking on the console event, you are gaining asynchronous access to it.

    Side Effects

    A side effect is making an HTTP request and saving the response to the component's state.

    In React

    Components in React have methods that are executed during the component's various phases. These are referred to as lifecycle methods.

    It takes a lot of practice to find out when and how to employ different lifecycle methods. Regardless, componentDidMount with class components and useEffect with functional components are the most important for HTTP requests.

    Example:

    We generated the component in App.js and styled it in App.css, using the API endpoint from http://jsonplaceholder.typicode.com/users. We can receive data from API endpoints with the targets "id", "name", "username", and "email".

    Step 1: npx create-react-app api-app

    After executing this command successfully, you will see a folder structure like this:

    Migrating From jQuery to React? Here’s How!

    Step 2: cd api-app

    Step 3: Write the following code in App.js in src folder:

    import React from "react";
    import './App.css';
    class App extends React.Component {
    
    // Constructor
    constructor(props) {
    super(props);
    
    this.state = {
    items: [],
    DataisLoaded: false
    };
    }
    
    // ComponentDidMount is used to
    // execute the code
    componentDidMount() {
    fetch(
    "https://jsonplaceholder.typicode.com/users")
    .then((res) => res.json())
    .then((json) => {
    this.setState({
    items: json,
    DataisLoaded: true
    });
    })
    }
    render() {
    const { DataisLoaded, items } = this.state;
    if (!DataisLoaded) return <div>
    <h1> Pleses wait some time.... </h1> </div> ;
    
    return (
    <div className = "App">
    <h1> Fetch data from an api in react </h1> {
    items.map((item) => (
    <ol key = { item.id } >
    User_Name: { item.username },
    Full_Name: { item.name },
    User_Email: { item.email }
    </ol>
    ))
    }
    </div>
    );
    }
    }
    
    export default App;

    Step 4: Write the following code in App.css in src folder:

    .App {
    text-align: center;
    color: Green;
    }
    .App-header {
    background-color: #282c34;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: calc(10px + 2vmin);
    color: white;
    }
    .App-link {
    color: #61dafb;
    }
    
    @keyframes App-logo-spin {
    from {
    transform: rotate(0deg);
    }
    to {
    transform: rotate(360deg);
    }
    }
    
    export default App;  

    Step 5: Run the app using npm start

    Output: You can see the output in http://localhost:3000/

    Migrating From jQuery to React? Here’s How!

    In jQuery

    The basic AJAX functionality of jQuery is one of its best features. This makes it simple to incorporate data from other websites and services into your own. It will also allow you to become less reliant on the widgets provided by companies, allowing you to design your own.

    AJAX (Asynchronous JavaScript and XML) is a collection of tools for making server calls and retrieving data.

    Example:

    We'll use a free API to pull employee names from an employee object and show them in a list. On the internet, there are numerous APIs that are available for free. You can utilize any of them.

    Let's look at the steps for Ajax Code and later on, we can add the HTML code to complete it.

    1. The first step is to obtain the getElementById method for the button element.
    2. The next step is to add an eventListener to the button and provide it with a callback function.
    3. Using the new keyword, create an XHR object.
    4. Using the open function, open an object. The first parameter is the type (GET or POST), the second is the API URL, and the third is a boolean value (true means asynchronous call and false means synchronous call).
    5. To display the data, we'll now use the onload function. After the API call is completed, the onload method is called. The success code for an HTTP request is 200, therefore we're testing it with that.
    6. We'll now convert it to a JSON object so we can quickly retrieve info from it.
    7. We'll use a loop to go over all of the items in the object and add them to the list using the innerhtml property in this step.
    8. The final step is to use the send() function to send the request.

    Complete code:

    <!DOCTYPE html> 
    <html lang="en">
    
    <head>
    
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width, 
    initial-scale=1, shrink-to-fit=no" />
    
    <link rel="stylesheet" href= 
    "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" 
    integrity= 
    "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" 
    crossorigin="anonymous" />
    
    <title> 
    AJAX in jQuery 
    </title> 
    </head>
    
    <body> 
    <button type="button" id="fetchBtn" 
    class="btn btn-success"> 
    Fetch Data 
    </button>
    
    <div class="container"> 
    <h1>Employee List</h1> 
    <ul id="list"></ul> 
    </div> 
    <script> 
    let fetchBtn = document.getElementById("fetchBtn"); 
    
    fetchBtn.addEventListener("click", buttonclickhandler); 
    
    function buttonclickhandler() { 
    
    // Instantiate an new XHR Object 
    const xhr = new XMLHttpRequest(); 
    
    // Open an obejct (GET/POST, PATH, 
    // ASYN-TRUE/FALSE) 
    xhr.open("GET", 
    "http://dummy.restapiexample.com/api/v1/employees", true);
    
    // When response is ready 
    xhr.onload = function () { 
    if (this.status === 200) { 
    
    // Changing string data into JSON Object 
    obj = JSON.parse(this.responseText); 
    
    // Getting the ul element 
    let list = document.getElementById("list"); 
    str = "" 
    for (key in obj.data) { 
    str += 
    `<li>${obj.data[key].employee_name}</li>`; 
    } 
    list.innerHTML = str; 
    } 
    else { 
    console.log("File not found"); 
    } 
    } 
    xhr.send(); 
    } 
    </script>
    
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" 
    integrity= 
    "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" 
    crossorigin="anonymous"> 
    </script>
    
    <script src= 
    "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" 
    integrity= 
    "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" 
    crossorigin="anonymous"> 
    </script>
    
    <script src= 
    "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" 
    integrity= 
    "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" 
    crossorigin="anonymous"> 
    </script> 
    </body>
    
    </html>

    Migrating from jQuery to React? Here’s how!
    When you click on the Fetch Data button, you will see a list of employees from a free API which we have used in our code.

    Migrating from jQuery to React? Here’s how!

    So, that’s how you can work with an API in jQuery.

    Migrating from jQuery to React

    Referencing DOM Elements

    Consider the following HTML document:

    <button id="btn-click"> Click Me</button>

    In jQuery:

    var $btnClick = $("#btn-click");$btnClick.on("click", function() {  alert("Button was clicked!");});

    A programmer should first use the $() method to access to the DOM element, giving either an id reference # or a class reference, as shown in jQuery. The click-event handler is instead given as the first parameter string to the on() function call of a query element.

    In React.js:

    In React.js, the displayed HTML UI is handled as part of the container, which is known as a component. All the elements which can only be presented in a target <div> will be included in the component. The <button> element will be removed from the original HTML code. Alternatively, you might use the <div> element as follows:

    <div id="react-root"></div>

    You'd have to create a component that renders the button in a separate JavaScript file first:

    import React from 'react';export default class ButtonComponent extends React.Component {  constructor(props) {    super(props);  }  handleButtonClicked() {    alert("Button was clicked!");  }  render() {    return (      <div>        <button onClick={this.handleButtonClicked.bind(this)}>          Click Me        </button>      </div>    );  }}

    Throughout the function call, a.bind(this) is often used to retain the value of this constant. This method exposes other methods that are either built-in to a React.Component, such as setState(), or user-defined. It could be claimed that an explicit reference was unnecessary. React.js and jQuery vary in that React.js saves all of its UI demands, but jQuery expects also that UI element is displayed in HTML.

    Managing State

    Assume you have a variable called message in your application that represents a shoutout. You'd like that message to appear within a container div like this:

    <div id="message">Message goes here</div>

    In jQuery

    In a jQuery approach, everything is still read from top to bottom.

    var message = $("#message").html();

    You must re-reference the <div> and insert the new value to update the message:

    var message = "New message"; // Normally set by some other logical routine$("#message").html(message);

    This method has the drawback of requiring the message to be set twice: once to extract the value and also to give a new value. The message must also be returned to the target <div>, which necessitates the use of additional code. This can get a little complex, especially if you have another procedure that might affect the value of the message. In that situation, you'd have to call $("#message").html(message) once more.

    In React.js

    React.js overcomes this problem by maintaining only one instance of a variable in a component's state. Each React.js component has a state object that is created in the component's state object. Consider the instance where you wish to preserve same message value, but any logical routine that modifies it will be reflected in the component's UI. One or more of the following may be present:

    import React from 'react';export default class MessageComponent extends React.Component {  constructor(props) {    super(props);    this.state = {      message: ""    }  }  updateMessage(message) {    this.setState({      message: message    });  }  render() {    return (      <div>        {this.state.message}      </div>    );  }}

    We can set the message in the component's state in the constructor. The updateMessage(message) method of the component invokes the setState() method of the component to update the message's value. The concept is that whenever setState() is invoked, the component will re-render the UI as it was in render(), because render() produces JSX, which displays the message via this.state.message with whatever value it has at the time.

    React vs jQuery – which to use when

    Once you've ported a large amount of code to React, you can start building component trees and communicating with props and callbacks between them.
    React.js might seem confusing intially, but still it uses good state management to keep things structured in the long term. Although jQuery is straightforward to use, it becomes unstable when more code is brought into the equation.
    If you're planning to switch from jQuery to React.js, keep the following in mind:

    • Create your components as stand-alone UI elements that can be positioned anywhere on your page.
    • To control how values are rendered by a component, use state variables and utility methods within the component.
    • A call to setState() causes the component's UI to be re-rendered with the updated state values using render().
    Profile

    Abhresh Sugandhi

    Author

    Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon