Diego
Diego

Reputation: 268

React App - materialize-css doesn't initialize on first render

I am building a 'Add Item' functionality with React and materialize-css. For some reason, the materialize-css components are not being initialized when i first navigate into the page they are on. They do initilize though after I refresh the page. I spent several hours trying to figure out the problem but couldn't find what i did wrong. I installed materialize-css via npm and here is my code where i initiliaze the materialize-css components:

    componentDidMount() {
    var context = this;
    document.addEventListener('DOMContentLoaded', function() {

        var elemsTwo = document.querySelectorAll('select');
        var instancesTwo = M.FormSelect.init(elemsTwo, {});

        var elemsThree = document.querySelectorAll('.timepicker');
        var instancesThree = M.Timepicker.init(elemsThree, {});
      });
}

Like I said it does work fine after refreshing the page, but when just navigating into the page, it doesn't work. Below are the screenshots on how the page looks before and after refreshing (refer to fields 'Gender' and 'Spoken Languages' on screenshots). Thanks in advance.

After

Before

Upvotes: 0

Views: 192

Answers (1)

Thomas Kekeisen
Thomas Kekeisen

Reputation: 4406

Its a bad practice to use React while using DOMContentLoaded on your own. Your main problem is, that DOMContentLoaded is fired when your content is ready, but this does not mean that React has done its initialisation. Also, DOMContentLoaded is not fired when you navigate between pages using React.

You may use a library that already closes this gap, like https://material-ui.com/.


If you want to stay with your concept, you have to call the code you run in your componentDidMount also when your navigator changed the page.

Upvotes: 1

Related Questions