Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
The "Class constructor cannot be invoked without 'new'" error occurs for 2 reasons:
new
operator.Component
class in a React.js application.Here is an example of how the error occurs.
class Person { constructor(first, last) { this.first = first; this.last = last; } getName() { return `${this.first} ${this.last}`; } } // ⛔️ Class constructor Person cannot be invoked without 'new' const p1 = Person('James', 'Doe');
To solve the "Class constructor cannot be invoked without 'new'" error, use
the new
operator when instantiating the class. The new
operator allows us to
create an instance of a class.
class Person { constructor(first, last) { this.first = first; this.last = last; } getName() { return `${this.first} ${this.last}`; } } // 👇️ use `new` operator const p1 = new Person('James', 'Doe'); console.log(p1); // 👉️ {first: 'James', last: 'Doe'} console.log(p1.getName()); // 👉️ "James Doe"
We used the
new operator
upon class instantiation. The new
operator does 3 things:
this
keyword to the newly created object.If you got the error inside of a React.js
application, you most likely
forgot to extend from the Component
class.
import React from 'react'; // ⛔️ Class constructor App cannot be invoked without 'new' class App { render() { return <div>Example</div>; } } export default App;
To solve the "Class constructor cannot be invoked without 'new'" error, extend
the Component
class when defining a class in a React.js application, e.g.
class App extends React.Component {}
.
import React from 'react'; // ✅ Now extending Component class class App extends React.Component { render() { return <div>Example</div>; } } export default App;
The extends
keyword allows us to specify that the App
class is a child of
the Component
class. In other words, App
is a subclass of Component
.