Search code examples
javascripthookmaterializeparallax

Materialize css parallax images disappear after navigating away to a different route and then back


I have used materialize css as per below code to create the parallax affect on 3 images. When the web page loads in dev server, it all runs perfectly, however if I navigate away from the page to a different component and then back again, all the parallax images disappear almost as if the parallax library is not working anymore. If I reload the webpage they all re-appear again as normal.

import React, { Component } from 'react'
import code from '../images/code.jpg';
import coffee from '../images/coffee.jpg';
import mac from '../images/mac.jpg';
import M from 'materialize-css/dist/js/materialize.min.js';

export default class About extends Component {

componentDidMount() {

    document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.parallax');
    var instances = M.Parallax.init(elems, {});
 });
}


 render() {

     return (

             <div>


                <div className="parallax-container">
                    <div className="parallax"> <img className="responsive-img" src={coffee}
                </div>  

                <div className="parallax-container">
                    <div className="parallax"> <img className="responsive-img" src={coffee}
                </div>   

               <div className="parallax-container">
                    <div className="parallax"> <img className="responsive-img" src={coffee}
                </div>    

          </div>


      )
 }

Solution

  • You don't need the addEventListener in your componentDidMount. It's not needed as the componentDidMount life-cycle method gives you the hook you're after for initializing any libraries you want to use in your component (parallax in your case). The reason why your parallax images disappear when switching between routes is probably because DOMContentLoaded isn't firing anymore when switching between routes and thus your parallax library isn't being initialized.

    Please have a look at React's life-cycle diagram to better understand how these life-cycle methods work: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/