0

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>


      )
 }
  • There is a special react library: http://react-materialize.github.io/react-materialize/?path=/story/react-materialize--welcome You should not mix up normal js DOM loading with react unless you know what you are doing. – Dimitri L. Oct 27 '19 at 15:04

1 Answers1

1

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/

tony
  • 155
  • 1
  • 2
  • 10
  • This should work in most cases, however it can also fail because the parent component is not yet mounted as explained here: https://stackoverflow.com/questions/36049493/when-exactly-is-componentdidmount-fired/36056794#36056794. To really check for the element in the DOM you can use refs https://reactjs.org/docs/refs-and-the-dom.html however I would encourage everyone not to do it if there is another way. – Dimitri L. Oct 27 '19 at 15:07
  • Thanks very much, I removed the addEventListener and it works perfectly now. I will review the link you sent. – RussellDrives Oct 27 '19 at 15:11