Yanick Rochon Yanick Rochon - 4 months ago 15
jQuery Question

Apply JavaScript to the layout in React after route is rendered

Using Meteor 1.4, Flow Router, and React, I need to execute some JavaScript code to initialize the layout. Currently, I have this

FlowRouter.route('/', {
name: 'Home',
action() {
mount(MainLayout, {
content: <div>Home</div>
});
}
});


And I need to execute this

$(function () {
$('.button-collapse').sideNav();
$('.parallax').parallax();
});


on the Layout HTML. This piece of code should be executed every time
MainLayout
is being rendered, and the same layout will be used in other routes (obviously!).

Where should I put the layout initialisation code?

Answer

Put it in your component's componentDidMount function:

class MainLayout extends React.Component {
  componentDidMount() {
    $('.button-collapse').sideNav();
    $('.parallax').parallax();  
  }
}

...unless you want to re-run those on updates (like when props including children change):

class MainLayout extends React.Component {
  componentDidMount() {
    this.isMounted = true; 
    this.initialiseJQueryWidgets();
  }

  componentDidUpdate() {
    if (this.isMounted) // In case you're doing server-side rendering
      this.initialiseJQueryWidgets();
  }

  initialiseJQueryWidgets() {
    $('.button-collapse').sideNav();
    $('.parallax').parallax();  
  }
}
Comments