Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best way import jQuery plugins or external client scripts? #856

Closed
manhhailua opened this issue Sep 16, 2016 · 21 comments
Closed

Best way import jQuery plugins or external client scripts? #856

manhhailua opened this issue Sep 16, 2016 · 21 comments

Comments

@manhhailua
Copy link

My projects comes with quite many external jQuery plugins. And I got troubles to import them into a specific component and make them work with development mode by npm start (server side rendering).
My current solutions is to add them all to the bottom of Html.js return func. But, this way increases page load.

@manhhailua manhhailua changed the title How to import jQuery plugins Best way import jQuery plugins or external client scripts Sep 16, 2016
@manhhailua manhhailua changed the title Best way import jQuery plugins or external client scripts Best way import jQuery plugins or external client scripts? Sep 16, 2016
@frenzzy
Copy link
Member

frenzzy commented Sep 19, 2016

Add link to jQuery lib to your Html.js and use plugins inside componentDidMount function

@manhhailua
Copy link
Author

@frenzzy : there will be too many things in Html. Is that good?
My Html is now like this!
Html

@codetony25
Copy link

I usually add external vendor libraries in /assets/

@manhhailua
Copy link
Author

@codetony25 : would you please show some peaces of code?

@minhnguyenwp
Copy link

minhnguyenwp commented Jun 21, 2017

I have same problem with this.
how can i use jquery plugin in React comp.
i did:

  • import jquery plugin in Html.js
  • in componentDidMount of Component i run .slick({...})

and i got this error.
screen shot 2017-06-21 at 2 14 22 pm

My code
screen shot 2017-06-21 at 2 18 37 pm

@frenzzy
Copy link
Member

frenzzy commented Jun 21, 2017

If third-party plugins change DOM, you need to create uncontrolled components for them, i.e.

shouldComponentUpdate() {
  return false;
}

And I do not see where you add slick plugin to jQuery

@manhhailua
Copy link
Author

manhhailua commented Jun 21, 2017

@minhnguyenwp : please stop importing jQuery into your component, that will increase the time on bundling process of Webpack and the size of bundle.js/vendor.js file as well. Just add a <script /> tag which has src attribute link to your jquery file and use $ in every components' componentDidMount functions without re-importing jQuery.

Be aware of eslint alert that '$' is not defined, put a comment /* global $ */ on top of your files or update .eslintrc.js file at globals property to ignore this alert.

Anyway, using jQuery to handle the DOM might cause React DOM tree crash (React indexes all the actual rendered DOMs by it virtual DOM tree). So, please ensure you read these posts before getting your hands dirty with React and jQuery co-operation.

  1. https://facebook.github.io/react/docs/refs-and-the-dom.html
  2. https://facebook.github.io/react/docs/uncontrolled-components.html
  3. https://facebook.github.io/react/docs/integrating-with-other-libraries.html
  4. https://medium.com/@shuvohabib/using-jquery-in-react-component-the-refs-way-969de9aa651f

@minhnguyenwp
Copy link

Hi @manhhailua ,
thank you so much for your reply.
i pretty sure to know using jquery is limited in react. but in this case i need to do that.
So could you tell me more about. eslint alert that '$' is not defined.
i imported jquery in html and jquery plugins too.
and i get that issue.
screen shot 2017-06-21 at 4 19 02 pm
screen shot 2017-06-21 at 4 18 55 pm

@manhhailua
Copy link
Author

manhhailua commented Jun 21, 2017

@minhnguyenwp : .slick function does not belong to origin $ or jQuery object. Moreover, Webpack separates each package that is imported to a component, so you cannot call .slick via $ or jQuery object if you continue importing jQuery this way. Sorry.

@minhnguyenwp
Copy link

minhnguyenwp commented Jun 21, 2017

@manhhailua I did like your words.

  1. Html.js
<script src="js/jquery.js"></script>
<script src="js/plugins.js"></script>
  1. in Component, no longer importing jQuery or jQ plugin.
  2. Just using $('...').slick()

Please show me a right way. im just a new-comer in react.

@manhhailua
Copy link
Author

@minhnguyenwp : are you currently using React-Starter-Kit? You wrote the right way in your most recent comment. Try it.

@Dr-Steve
Copy link

Also having trouble with this. I imported jquery and a plugin in index like so:

<script src = "imports/jquery-3.2.1.js"></script>
<script src = "imports/jquery.form.min.js"></script>

And I still get $ is undefined. If I import jquery in the component with:

import $ from 'jquery';

I can use jquery, but then I can't use my plugin.

@manhhailua
Copy link
Author

@Dr-Steve you should not import jQuery. Just attach it via <script> tags and you're good to go use it inside componentDidMount.

@rorteg
Copy link

rorteg commented Mar 22, 2018

Create one component jQuery, example (components/Jquery.js:

import React from 'react'
import jQuery from 'jquery' // Import directly from node-modules
window.jQuery = jQuery

export default () => (jQuery)

In your component you will use a jQuery plugin, example (components/Slider.js):

import React, {Component} from 'react'
import $ from './Jquery' // Import component
import flexSlider from 'flexslider' // Import directly from node-modules

class Slider extends Component {
    componentDidMount() {
         $(".hero-slider").flexslider({
            controlNav: true,
            directionNav: false,
            animation: "fade"
        });
    }

    render = () => (
        <div className="hero hero-slider">
	    <ul className="slides">
	        <li data-bg-image="dummy/slider-1.jpg">
		    <div className="container">
                         <h3 className="slider-subtitle">Your header goes here</h3>
			<h2 className="slider-title">Professional</h2>
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa molestiae necessitatibus possimus ducimus facere, error, nostrum. Quos sapiente ducimus maxime odio alias dolor consequuntur, maiores commodi exercitationem veniam. Id, ex?</p>
			<a href="#" className="button large">Read more</a>
		    </div>
		</li>
                 <li data-bg-image="dummy/slider-2.jpg">
		    <div className="container">
		        <h3 className="slider-subtitle">Your header goes here</h3>
			<h2 className="slider-title">Professional</h2>
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. In maiores illo eligendi obcaecati reiciendis, vel perspiciatis aliquid esse architecto deleniti asperiores, laboriosam nemo rerum! Ipsam numquam delectus minus iure sit!</p>
			<a href="#" className="button large">Read more</a>
		    </div>
		</li>
		<li data-bg-image="dummy/slider-3.jpg">
		    <div className="container">
			<h3 className="slider-subtitle">Your header goes here</h3>
			<h2 className="slider-title">Professional</h2>
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam iure, alias error suscipit porro quidem minus, autem repellendus rerum labore corrupti! Quia quas, architecto, quis non pariatur quisquam nisi magnam.</p>
			<a href="#" className="button large">Read more</a>
		    </div>
		</li>
	    </ul>
	</div>
    )
}

export default Slider

@manhhailua
Copy link
Author

@rorteg there's going to be unit testing issue on your solution.

@rorteg
Copy link

rorteg commented Mar 22, 2018

@manhhailua I'm a beginner in frontend, I work more with backend and I have no experience with frontend unit testing. Could you give me a more detailed answer as to why I would have problems with the tests?

@manhhailua
Copy link
Author

manhhailua commented Mar 22, 2018

@rorteg

  1. window is a browser instance. Most of time you test or bundle in nodejs environment where window is definitely undefined. jsdom or karma can handle this issue, but you will have to spend more time on further mocking and configuration.
  2. flexslider is also a component and you can't test it. You should wrap it by a react component.
  3. if flexslider somehow changes the rendered DOM you will not able to test it and react will throw errors.

@AbdelhafidFutureTrendz
Copy link

I have this error !!

ERROR in ./src/components/home/slider_section_element/FlexSlider.js
Module not found: Error: Cannot resolve module 'flexslider' in /Volumes/Data/Front_Project/my-project-name/src/components/home/slider_section_element
@ ./src/components/home/slider_section_element/FlexSlider.js 29:18-39

@mgolshan-talentnet
Copy link

Follow this solution:
https://stackoverflow.com/a/33351325/4980017

@gucompi
Copy link

gucompi commented Mar 28, 2019

@frenzzy : there will be too many things in Html. Is that good?
My Html is now like this!
Html

thank you!

@Zill-Saqee
Copy link

hello everyone , can anyone please help in this problem I am doing conversion from html template to react project.In html template external libraries like jquery , chosenjs are used but when i add them in index.html file of react project following error message is shown on console window and these libraries arenot working
err1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants