Author avatar

Vivek Kumar

Walkthrough of Mobile Rendering for jQuery and React – Part 2

Vivek Kumar

  • Jun 18, 2019
  • 9 Min read
  • 13 Views
  • Jun 18, 2019
  • 9 Min read
  • 13 Views
Web Development
React

Introduction

In the previous guide, we focussed on the first two methods related to the integration of React with an already existing jQuery mobile. Our prime objective in this guide is to throw some light on the third approach of integration which is based on the Publisher/Subscriber Model.

The Baseline

One of the key advantages of this model is its dynamic approach. It follows a way by which the component and the mobile application synchronize with one another which makes the application of this model a unique one. In this model, the user can authorize the component to listen to the updates coming from the outer end of the mobile application. Apart from that, it is also competent enough to send the updates back. Let’s look at an example: at the time when the user interacts with an existing mobile application, there are certain events that can trigger approaches which are, thereafter, dispatched to a React component. This is the reason why it can update itself automatically without any sort of external influence.

Imgur

In the above diagram, one can see the React component applying a publisher/subscriber model in order to listen to the events associated with the parent app.

The flow chart simply replaced the UI manager class via the publisher/subscriber model. The response, as well as the changes taking place in the background, can be observed in the images below:

Imgur

Imgur

Kory Becker has presented a live demo of the same which can be accessed on the given webpage.

Here, for instance, if the user clicks the button located inside jQuery app then the event can get dispatched to all the subscribers within the intermediate JS class. That will automatically permit them to act accordingly.

The implementation of this kind of design with pub/sub-manager class can be seen in the programming codes mentioned below:

1
2
3
4
5
6
7
8
9
10
11
12
var PubSubManager = {
  subscribers: [],
  subscribe: function(parent, callback) {
    this.subscribers.push({ parent: parent, callback: callback });
  },
  color: function(name) {
    // Notify subscribers of event.
    this.subscribers.forEach(function(subscriber) {
      subscriber.callback(name, subscriber.parent);
    });
  }
};
javascript

The class which has been mentioned above has a subscriber approach. The approach enables the clients to get notified of the events taking place from the parent application. In this specific case, when the color approach is requested by an existing application, it is possible for any number of subscribers to get notified about the change, facilitating them update their internal UIs simultaneously without any sort of manual intervention.

For instance, take the example of a case wherein the image above the current application changed the color of a square presented on the page in the fraction of a second. The color will alter from red to green, and vice versa, as per the sequence of the codes mentioned below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$(function() {
  setTimeout(function() {
    ReactDOM.render(React.createElement(MyComponent, { context: PubSubManager }), document.getElementById('root'));
  }, 0);
  // Change the box color every few seconds.
  setInterval(function() {
    var box = $('#box');
    var color = box.css('background-color') === 'rgb(255, 0, 0)' ? 'green' : 'red';
    // Change box color.
    box.css('background-color', color);
    // Notify subscribers.
    PubSubManager.color(color);
  }, 1000)
});
javascript

In the above code, one can see a phase, or a time period, to change the square color in the fraction of a second. In the general circumstances, it is the React component that will have no admission to the right of detecting the changes taking place in the color of the square. Additionally, it would not have any direct access to the UI element at all. It is basically happening due to the fact that the square is div situated outside the range of the React component.

Nevertheless, with the involvement of the publisher/subscriber model, the React component will have the authorization to demand notification on every occasion where a change in the square color takes place. It will enable the React component to update its own UI with a response to the changes taking place in the elements.

The React Component

Here, the React method exposes the show and hide methods, as shown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
      isVisible: false
    };
    
    this.onSpeak = this.onSpeak.bind(this);
  };
  show(text, callback) {
    this.setState({ isVisible: true, text: text, callback: callback });
  }
  hide() {
    this.setState({ isVisible: false });
  }
  
  onSpeak() {
      this.state.callback('Hello world! This is the MyComponent control.');
  }
  
  render() {
    return (
      <div className = { 'my-component ' + (this.state.isVisible ? '' : 'hidden-xs-up') } >
        <div className = "card" >
          <div className = "card-header" >
            My Component
          </ div>
          <div className = "card-block" >
            <h4 className = "card-title" ></ h4>
            <p className = "card-text" >
              { this.state.text }
            </ p>
            <a href = "#" className = "btn btn-primary" onClick = { this.onSpeak } > Speak </ a>
          </ div>
        </ div>
      </ div>
    );
  }
};
javascript

Calling React Component Methods Directly from Outside

Apart from the above-mentioned model and the models that we discussed in the previous guides, the communication between jQuery and React can take place in reverse fashion. Yes, right from jQuery to React by calling the methods directly inside the React component.

By the time the rendering of the React component has been done, one can directly make call methods inside React components. By that approach, the user can take command of the React component from the outside (for instance, via jQuery), calling different methods existing in React class that can alter the state, the UI and the other sorts of behavior outputs of the React Application.

Calling for the React Methods from the Outside

Let us have a glance over a simple example calling the React component approach outside of the jQuery application.

1
2
3
4
<button id='btnShow' type="button" class="btn btn-primary">Show</button>
<button id='btnHide' type="button" class="btn btn-primary">Hide</button>
<div id="root" class='mt-5'></div>
<div id="output"></div>
html

The demo can be accessed from here.

In the above-mentioned HTML code, there are two buttons meant for the display of show and hide. Apart from that, we also have a root div, as the phase where the rendering of the React component will take place. Last but not least, the user will have an output div displaying the text generated out of the React component.

Conclusion

After the completion of this and the previous guide, which covers the broad topic mobile rendering for jQuery and React, we have successfully completed an overview of three diverse methods for mobile rendering. All three methods are different in their approach and have the capacity to give a wide range of design methodologies on an individual basis permitting React component interaction with the UI components located outside the parameter of its internal elements.

It is an undeniable fact that there are multiple ways accessible to procure identical designs. One can even refer jQuery on a direct basis and choose the elements as per their convenience. Nonetheless, it wouldn’t allow the user to have access over the scope/context of the outer mobile app itself, until the state values are accumulated inside data attributes of HTML components. Or, by allowing the passage of React component in a span of application’s backdrop, the user permits integration of the React element to the current jQuery mobile app, with slight to no commotion within the rest of the mobile app.

0