Wednesday, May 2, 2018

Enhance parts of multi page application with react or vue

Leave a Comment

I'm developing a enterprise application with java & hibernate & spring mvc in the server side and using jquery in the client side (not a SPA).

Now in the search page i use ajax and get only json response, but i don't want to write something like this below in every search or pagination request.

function(ajaxData) {     ....     $('#search').html('' +         '<div class="search-container">' +            '<div class="search-item">' +              '<div class="title-item">'+ajaxData.title+'</div>' +               ...              ...           '</div>' +          '</div>'     )     .... } 

I think it's easy to use jsx with a react or vue component just in this page to refresh the results.

I want also reuse some html blocks and i think it will be easy with react or vue

I used to build a little SPA project and it's all about npm and webpack and bundling, but i really don't want to use them since i have a multi page application and it's very suitable for my project.

I think the same thing facebook is doing, they use react but facebook is not a SPA.

How can i achieve this hybrid approach ?

4 Answers

Answers 1

Since you have an existing multi page application without a build step (that is, without webpack/babel), I believe one very simple way of achieving what you want is using Vue.js.

You can define a template and update only the data.

Here's a demo of how you would do the code you showed in the question:

new Vue({    el: '#app',    data: {      ajaxDataAvailable: false,      ajaxData: {        title: '',        results: []      }    },    methods: {      fetchUsers() {        this.ajaxDataAvailable = false; // hide user list        $.getJSON("https://jsonplaceholder.typicode.com/users", (data) => {          this.ajaxData.title = 'These are our Users at ' + new Date().toISOString();          this.ajaxData.results = data;        	this.ajaxDataAvailable = true; // allow users to be displayed        });      }    }  })
/* CSS just for demo, does not affect functionality could be existing CSS */  .search-container { border: 2px solid black; padding: 5px; }  .title-item { background: gray; font-weight: bold; font-size: x-large; }  .result-item { border: 1px solid gray; padding: 3px; }
<script src="https://unpkg.com/vue"></script>  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>    <div id="app">    <button @click="fetchUsers">Click to fetch the Users</button><br><br>      <div class="search-container" v-if="ajaxDataAvailable">      <div class="search-item">        <div class="title-item"> {{ ajaxData.title }}</div>        <div class="result-item" v-for="result in ajaxData.results">          Name: {{ result.name }} - Phone: {{ result.phone }} - Edit name: <input v-model="result.name">        </div>      </div>    </div>    </div>

In this example, we have:

  • A method fetchUsers that will perform the ajax call;
  • The fetchUsers method is bound to the click event of the <button> via @click="methodName" (which is a shorthand to v-on:click="methodName").
  • A v-if (v-if="ajaxDataAvailable") that makes the .search-container div hidden until the ajaxDataAvailable property is true.
  • The rendering of some data in the template using interpolation: {{ ajaxData.title }}, note that this picks the value from the objects declared in the data: part of the Vue instance (the new Vue({... code) below and is automatically updated whenever ajaxData.title changes (what happens inside the fetchUsers method when the Ajax call completes.
  • The rendering of a list using v-for: v-for="result in ajaxData.results". This iterates in the ajaxData.results array, that is too updated inside the fetchUsers method.
  • The use of an <input> element with the v-model directive, which allows us to edit the result.name value directly (which also updates the template automatically).

There's much more to Vue, this is just an example. If needed, more elaborated demos can be made.

As far as integrating into an existing application, you could paste this very code into any HTML page and it would be already working, no need for webpack/babel whatsoever.

Answers 2

I had done a similar kind of stuff in the past. I injected a small react component into the DOM.

Here is how I did it:

Create a React component in JSX, let's call it Demo:

export class Demo extends React.Component {     render() {         return <h1>This is a dummy component.</h1>     } } 

Now use the renderToStaticMarkup function to get the static html.

const staticMarkup = renderToStaticMarkup(<Demo PASS_YOUR_PROPS/>); 

You have the HTML, now you can insert this markup at the desired location using the innerHTML.

Apologies if I misunderstood your question.

UPDATE

We could also use the render() for this purpose. Example:

document.getElementById("button").onclick = () => {   render(     <Demo PASS_YOUR_PROPS/>,     document.getElementById("root")   ); }; 

Working solution with render() and renderToStaticMarkup: https://codesandbox.io/s/w061xx0n38

render()

Render a ReactElement into the DOM in the supplied container and return a reference to the component.

If the ReactElement was previously rendered into the container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.

renderToStaticMarkup()

This doesn't create extra DOM attributes such as data-react-id, that React uses internally. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save lots of bytes.

Answers 3

So, there are two things you could do to re-use your code:

  • I would recommend React for sharing code as components. This page from Official docs explains how to use react with jquery. Additional resources for integrating react and jquery jquery-ui with react, Using react and jquery together, react-training
  • Or, use some template engine so you do not need to go through the trouble of integrating a new library and making it work alongside jquery. This SO answer provides lot of options for doing this.

Unless your planning on migrating your jquery app to react in the long run, I would not recommend using react just for one page. It would be easier to go with the template engine route.

Answers 4

From the looks of the requirement, you just need:

  1. Dynamic, data driven HTML blocks
  2. Which need to be reusable

In this case, since we don't need state, having an entire framework like react/vue/angular may be overkill.

My recommendation would be to go for a templating engine like jQuery Templates Plugin or Handlebars

You can even store the HTML blocks as separate reusable modules which you can invoke as needed across your pages.

Sample using Handlebars:

var tmpl = Handlebars.compile(document.getElementById("comment-template").innerHTML);    function simulatedAjax(cb){    setTimeout(function(){      cb(null, {title:'First Comment', body: 'This is the first comment. Be sure to add yours too'});    },2000);  }      simulatedAjax(function(err, data){    if(err){      // Handle error      return;    }    document.getElementById('target').innerHTML = tmpl(data);  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>    <div id="target">  Loading...  </div>    <script id="comment-template" type="text/x-handlebars-template">    <div class="comment">      <h1>{{title}}</h1>      <div class="body">        {{body}}      </div>    </div>  </script>

NOTE:

One disadvantage of using this approach (as opposed to a framework like react/vue/angular) is that you will need to handle event binding and unbinding manually. You can mitigate this to some extent by wrapping your templates in a function which mounts and unmounts it automatically.

// Single reuable JS file for each component  (function(namespace) {    var _tmpl = Handlebars.compile('<div class="comment"><h1>{{title}}</h1><p>{{body}}</p></div>');      function titleClickHandler(ev) {      alert(ev.target.innerHTML)    }      function CommentWidget(target, data) {      var self = this;      self.data = data;      self.target = document.querySelector(target);    }    CommentWidget.prototype.render = function() {      var self = this;      self.target.innerHTML = _tmpl(self.data);        // Register Event Listeners here      self.target.querySelector('h1').addEventListener('click', titleClickHandler)      }    CommentWidget.prototype.unmount = function() {      var self = this;      // Unregister Event Listeners here      self.target.querySelector('h1').removeEventListener('click', titleClickHandler);        self.target.innerHTML = '';      }      window._widgets.CommentWidget = CommentWidget;    })(window._widgets = window._widgets || {})      // Usage on your page   var w = new _widgets.CommentWidget('#target', {    title: 'Comment title',    body: 'Comment body is remarkably unimaginative'  });    // Render the widget and automatically bind listeners  w.render();    // Unmount and perform clean up at a later time if needed   //w.unmount();
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>    <div id="target"></div>

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment