Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

componentDidMount method not triggered when using inherited ES6 react class

I'm trying to use ES6 classes inside of React, and want all my components to inherit certain methods, however as soon as I try to extend a component which extends the React.Component class, the componentDidMount method doesn't trigger and hence nothing gets rendered. The code I'm using:

BaseComponent.jsx

import React from 'react';

class BaseComponent extends React.Component {

    constructor() {
        super();   
        console.log('BaseComponent constructor');
     }

     render() {
         return (
             <div>Hello, Im the base component</div>  
         );
     }
}

export default BaseComponent;

ExampleComponent.jsx

import BaseComponent from './BaseComponent';

class ExampleComponent extends BaseComponent {
     constructor(props) {

        super(props);
     }

     componentDidMount() {
         console.log('exampleComponent mounted');
     }

    render() {
        return (
            <div>Hello, Im the example component</div>  
        );
    }
}

export default ExampleComponent;

App.jsx

import React from 'react';
React.render(<ExampleComponent />, document.body);

I'm using React 0.13.3, and using babelify 6.1.2 to transpile.

The string 'exampleComponent mounted' never gets logged to console, and nothing is rendered. Any ideas what I'm doing wrong?

like image 556
Dan Rostron Avatar asked Jun 26 '15 12:06

Dan Rostron


Video Answer


1 Answers

I'm not sure about the approach, but this code also works:

export default class Service extends BaseComponent {
  componentDidMount(...args) {
    super.componentDidMount.apply(this, args);
  }
}

UPD: this is considered to be a bad practice though:

a) https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4 b) https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750

like image 191
Dmitrii Sorin Avatar answered Oct 12 '22 09:10

Dmitrii Sorin