Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery in react component

I have a web-app built with react. In this app I also have some pages with jQuery code from an old version. Right now this is rendered server side and i have to load the entire ejs file with jQuery and jQuery-UI code in script-tags with its own navigation menu. (Almost 1000 lines of jQuery code)

This means that I have to build another nav-menu for these jQuery pages.

I would like to render this jQuery depended code in my "content div" so I can still use the react menu which uses react router. I would like to render it like a component. But I don't know if this is the best solution.

I have read many examples of how this could be done, but I don't know which of them to go for and I have been strugling to make them work

Like shown in this example: Adding script tag to React/JSX This example adds script tags in componentWillMount

Or with import and require like this example: How to add script tag in React/JSX file?

I couldn't make these solutions work without installing jQuery through npm.

I have not yet installed jQuery through npm because I know this will affect my bundle size for the rest of the application and I am only using jQuery for a couple of my pages. The user don't really need to load jQuery for the rest of the app

What do you recommend in a situation like this? What is the best solution for performance and user experience?

like image 944
Koiski Avatar asked Nov 28 '17 14:11

Koiski


Video Answer


1 Answers

Take a look at react-async-component. Your component might look something like:

// SomethingWithJquery.js
import React, {Component} from 'react'
import $ from 'jquery'

class SomethingWithJquery extends Component {

  constructor(props) {
    super(props)
  }

  render() {
    // ... as much jquery mess as you need
  }

}

export default SomethingWithJquery

And wrapper in separate file:

// SomethingWithJquery.async.js
import { asyncComponent } from 'react-async-component';

export default asyncComponent({
  resolve: () => System.import('./SomethingWithJquery')
});

Than you can use it as regular react component, react-async-component will load entire component in separate .js file on purpose under the hood.

like image 107
Glen Swift Avatar answered Sep 21 '22 14:09

Glen Swift