javascriptecmascript-6reactjs

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"


Solution

  • 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>;
            }
        };