Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a parent class method in React?

I'm extending a base class and overriding a method in the base class. But when I call it, it calls the super class version. How do I override the method?

    var Hello = React.createClass( {

        getName: function() { return "super" },

        render: function() {

            return <div>This is: {this.getName()}</div>;
        }
    });

    class HelloChild extends Hello {
        constructor(props) {
          super(props);

          console.log( this.getName());
        }
        getName()
        {
          return "Child";
        }
    };

I want it to print "This is: Child" but it prints "This is: super"

like image 843
Don Rhummy Avatar asked Aug 04 '16 04:08

Don Rhummy


People also ask

How do I override a method in react JS?

To override a style, you have two options. Either you can pass a style object, or you can pass a function that will obtain props regarding the current internal state of the component, thus enabling you to modify styles dynamically depending on the component state, such as isError or isSelected .

How do you override Primereact CSS?

getElementById("root") ); You can make your React component's CSS (like "App") override the React Prime theming by importing the theme CSS as the first thing, then components after making their CSS later and higher precedence.


2 Answers

The problem is that you're mixing ES6 type class declaration (ex. Hello) with old school Javascript declaration (ex. HelloChild). To fix HelloChild, bind the method to the class.

class HelloChild extends Hello {
    constructor(props) {
      super(props);

      this.getName = this.getName.bind(this); // This is important

      console.log( this.getName());
    }

    getName()
    {
      return "Child";
    }
};

Then it'll work.

like image 68
Ryan Shillington Avatar answered Sep 17 '22 14:09

Ryan Shillington


I found the answer (adapted from here: https://gist.github.com/Zodiase/af44115098b20d69c531 ) - the base class needs to also be defined in an ES6 manner:

class Hello extends React.Component {

        //abstract getName()
        getName()
        {
            if (new.target === Hello) {
                throw new TypeError("method not implemented");
            }
        }

        render() {

            return <div>This is: {this.getName()}</div>;
        }
    };
like image 39
Don Rhummy Avatar answered Sep 17 '22 14:09

Don Rhummy