admin管理员组

文章数量:1303061

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-p"></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-p'));


  </script>
</body>

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

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-p"></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-p'));


  </script>
</body>

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

Share Improve this question edited Jun 17, 2016 at 17:11 MrWeb asked Jun 17, 2016 at 16:58 MrWebMrWeb 912 gold badges2 silver badges9 bronze badges 2
  • You could use the non-minified version to see the full error message. – Jack Commented Jun 17, 2016 at 17:01
  • @Jack Now I can see the full error message. Description updated. – MrWeb Commented Jun 17, 2016 at 17:10
Add a ment  | 

3 Answers 3

Reset to default 2

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

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

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.

本文标签: javascriptReactUncaught Invariant ViolationStack Overflow