In my current React + React-router setup my component imports some jQuery things (owl.carousel and magnific popup)
I want to keep the code clean, so the external features are stored in separate file. The code below works only when the page is loaded with direct URL and doesn't work when navigating back and forwards the app. So everything inside $(document).ready
is triggered only with direct link.
import '../jQuery/carousel.js';
$(document).ready(function(){
$('.owl-carousel').owlCarousel({
});
$('.popup-gallery').magnificPopup({
});
});
How do I manage this problem? I tried to use componentWillMount and wrap .ready() with some custom function, but I can't access updateJs()
in imported file
class MyComponent extends Component {
componentWillMount() {
updateJs();
}
}
ready() to call jquery function in react . You can make use of componentDidMount() just as your $(document). ready() to ensure that DOM is rendered. Then access jQuery dependent libraries as local variables to apply for DOM elemnets.
So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them.
history. push() is another approach where we make use of the history props React Router provides while rendering a component. In other words, this works when the component is being rendered by React Router, bypassing the component as a Component prop to a Route.
The jQuery document ready function executes when the DOM (Document Object Model) is completely loaded in the browser. jQuery document ready is used to initialize jQuery/JavaScript code after the DOM is ready, and is used most times when working with jQuery. The Javascript/jQuery code inside the $(document).
No need to use $(document).ready()
to call jquery function in react
.
You can make use of componentDidMount()
just as your $(document).ready()
to ensure that DOM
is rendered.
Then access jQuery
dependent libraries as local variables to apply for DOM
elemnets. Below example shows some light on this.
import $ from 'jquery'; //make sure you have jquery as dependency in package.json
class MyComponent extends Component {
componentDidMount() {
let owlCarousel = $.fn.owlCarousel; //accessing jquery function
let magnificPopup = $.fn.magnificPopup; //accessing jquery function
$('.owl-carousel').owlCarousel({ //call directly on mount
});
$('.popup-gallery').magnificPopup({
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With