Skip to content
Advertisement

react componentDidMount not firing

I set up a new react project and for some reason, the componentDidMount method is not being called.

I have verified this behavior by placing a call to console.log in componentDidMount but I cannot see its output in the console.

Furthermore, this.setState() is not working.

I’m pretty stumped as to why the componentDidMount is not being called. I tried using both React “v0.14.0” and “v0.14.3”.

Why is ‘componentDidMount’ not being called?

Code:

var React = require('react');

var RecipePage = React.createClass({
  componentDidMount: function() {
    console.log('mounted!');
  },
  render: function() {
    return (
      <div>Random Page</div>
    );
  }
});

module.exports = RecipePage;

Advertisement

Answer

So… lo and behold…. I finally got it working(with the help of a back-end expert). The reason why the “componentDidMount” methods weren’t firing was because my server was bundling and serving all the react + html stuff on server side. (Only “render” and “getInitialState” methods get called to create the “html” template that gets delivered through the client’s browser…but it stops there because it thinks it’s finished)

The fix: Find a way to deliver the resulting “compiled” html through the server AND in addition, allow react’s own events to be accessible and “fireable” again on the client side. When compiling my “view” file( index.js or index.html ), I included an “Application.start()” script that injects my bundle.js code into the template again. Then in my gulpfile, exported the “Application” variable so the “view” file can access it.

Gahh…pulled my hair out for this. Time to read up on server side vs. client side rendering

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement