Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhance parts of multi page application with react or vue

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 ?

like image 911
Hayi Avatar asked Apr 22 '18 13:04

Hayi


People also ask

Is React used for multi page application?

The use cases for having multiple pages in a single React app are pretty simple. You can create a website, and easily classify different types of content on different pages. But, it should also be understood that the default implementation of React is made to use a single HTML file, and this is by design.

Should I use Vue or React?

Overall, Vue might be the best choice if you're a newer developer and not as familiar with advanced JavaScript concepts, while React is quite well suited for experienced programmers and developers who have worked with object-oriented JavaScript, functional JavaScript, and similar concepts.

In which cases VueJS is better than React?

Vue. js combined the top-level features of React and Angular, but its main feature is the perfect user experience. Also, it leveraged the capacity of the virtual DOM and optimized the code structure.

Is Vue more performant than React?

Overall, Vue may offer higher performance speed and scale your projects. However, React. js has a better ecosystem, many templates, and extra tools. This is why teams on smaller projects often opt for Vue, because speed is a decisive factor, whereas React fits complex web platforms better.


2 Answers

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.

like image 148
Shishir Anshuman Avatar answered Oct 11 '22 13:10

Shishir Anshuman


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.

like image 40
acdcjunior Avatar answered Oct 11 '22 13:10

acdcjunior