MrWeb
MrWeb

Reputation: 91

React - Uncaught Invariant Violation:

When I run my code on browser, I'm getting this error message.

Uncaught Invariant Violation: MyComponent.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

I'm using Atom as my code editor and running on a chrome web server. Here is my code.

<body>
<div id="react-comp"></div>
  <script type="text/babel">
    var MyComponent = React.createClass({
      render: function() {
        return
          <div>
            <h1>{this.props.text}</h1>

          </div>;
      }
    });

    ReactDOM.render(
      <div>
        <MyComponent text="Hello World"/>
        <MyComponent text="Hello"/>
      </div>  
    , document.getElementById('react-comp'));


  </script>
</body>

It might be a jsx transforming issue? or any other thing?

Upvotes: 3

Views: 15670

Answers (3)

modernator
modernator

Reputation: 4427

I don't know which version of React you are using, as I know some old version makes error if the JSX syntax isn't wrapped with (). Try to do this on MyComponent's render method:

render: function() {
    return (
      <div>
        <h1>{this.props.text}</h1>
      </div>
    );
  }

Upvotes: 2

Chris
Chris

Reputation: 59501

Just change your render function to

var MyComponent = React.createClass({
  render: function() {
    return (
      <div>
        <h1>{this.props.text}</h1>    
      </div>
    );
  }
});

Daniel's suggestion is also correct.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190935

You are likely hitting JavaScripts automatic semicolon insertion after return. Just remove the line break before your div.

var MyComponent = React.createClass({
  render: function() {
    return <div> // Change this line
        <h1>{this.props.text}</h1>

      </div>;
  }
});

Upvotes: 2

Related Questions