Jonas Barenfeld Jonas Barenfeld - 3 months ago 11
React JSX Question

React.js Uncaught Error: Invariant Violation

After getting frustrating from the react_rails gem because of the lack of support for Commonjs modules, i'm testing the react_webpack_rails gem from netguru. but since then i got an Invariant Violation.

For example, if i'm writing a simple Hello World component in ES6 syntax :

import React from 'react';

class tasksBox extends React.Component {
render() {
return <div>Hello World</div>;
}
}

export default tasksBox;


raise these errors :

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.


your help will be much appreciated, i can't figure where the error come from.

Answer

When creating a class in React, you are supposed to call super on props in the constructor if you want to have a state. Here are a few things you can change and or try:

export class TasksBox extends React.Component {
    constructor(props){
        super(props);
        this.state = {};
    }
    render() {
        return <div>Hello World</div>;
    }
}

You can export the class inline and create the state, which can cause issues. Also notice I changed the name to start with a capital letter TasksBox instead of tasksBox as React wants your class name to start with a capital letter

Comments