'React-router : How to trigger $(document).ready()?

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();
  }
}


Solution 1:[1]

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({
    });
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jyothi Babu Araja