Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a React Component in an existing jQuery application on jQuery click

I have an existing single page application build in jQuery/HTML. I can't rewrite the existing application in React because it's very big.

I am planning to build new screens in that existing application with React. However I wonder, how can render React screens on click of a button/link from existing navigation?

It's something like, the click handler function is a normal JavaScript which is outside the React component and inside a handler function I have to write code to load new screen which is made in React Component.

I am not directly including react.js and react-dom.js in index.html, rather i am creating a bundle.js by using babel and webpack. So accessing ReactDOM.render outside bundle.js is throwing error.

like image 640
arun bahal Avatar asked May 31 '18 11:05

arun bahal


1 Answers

With React, you use ReactDOM.render to attach layout created with React component to the DOM.

It does not really matter to which DOM node to attach, or when you call that function. The usual way is to do it on page load, but you can do it when a button is clicked just as well.

It could look something like this:

$('#my-button').click(() => ReactDOM.render(<MyApp />, $('#my-container')[0]);

In this example, <MyApp /> would the root component of your React layout, and my-container would be some div on the page where you want to put the React layout.

What if I'm not using a module bundler?

If your existing page does not use any module bundler like webpack, you cannot easily import ReactDOM or use JSX notation in your plain jQuery code.

In this case, set up a webpack build to create the React layout and expose a global function that adds the React layout to the DOM. A beginner-friendly way to do this is using create-react-app.

CRA can create a bundle that includes your JSX code and all the libraries you need. You include it in your page with a script tag, just like you include the jQuery library.

In your React app, create a global function that adds the React layout to the DOM, for example:

window.renderMyReactApp = element => ReactDOM.render(<MyApp />, element);

In the jQuery code on your HTML page, call the function like so:

$('#my-button').click(function() {
  window.renderMyReactApp($('#my-container')[0]);
});
like image 97
Patrick Hund Avatar answered Nov 14 '22 20:11

Patrick Hund