27
votes

I'm building a small react js application and I get this error:

Uncaught Error: Invariant Violation: exports.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

These are my source files: App.jsx

var React = require('react');
var Chats = require('./chats');
var messages = {
  chatMessages: [{
    name: ' John Doe',
    message: ' Hey Lisa, how are you doing?'
  },{
    name: 'Lisa Johnson',
    message: 'Pretty good, how are you?'
  }]
}
var App = React.createElement(Chats, messages)
React.render(App, document.querySelector('.container'));

Chats.jsx

var React = require ('react');
var Chat = require ('./chat');

var Chats = React.createClass({
  render:function(){
    var chats = this.props.chatMessages.map(function(chatProps){
      return <Chat {...chatProps} />
    });
    return (
      <div>
        {chats}
      </div>
    )
  }
});

module.exports = Chats;

And Chat.jsx

var React = require ('react');

var Chat = React.createClass ({
  render:function (){
  return
    <div>
      <p>{this.props.name}</p>
      <span> {this.props.message} </span>
    </div>

}
});

module.exports = Chat;

I think the problem is in my map function but I really want someone to tell me where I made the mistake.

1
You returned an array of Chat elements from the Chats render function; they need a parent element. Try <div>{chats}</div> instead (or the JSX-less equivalent).Josh David Miller
Hey Josh, thanks for the comment, after wrapping {chats} into divs the error still persists and also the unique key warning appeared.loliki
Can you update your code above to reflect the current state? Also, you will need a key prop for each item in an array that points to an unique id of some kind so React knows which DOM nodes are for the same data when it renders again.Josh David Miller
I just updated the above code, I will add the unique keys as soon as I get rid of this error :) Thanksloliki
Try wrapping the tags in parentheses: return (<div>...</div); And can you identify which line is causing the error?Josh David Miller

1 Answers

35
votes

I downloaded your code from GitHub. The problem was, as I suspected, wrapping components in parentheses on the return. From your updated code above, you did not do this on the Chat component. This is necessary because the transformed value of React.createElement will reside on the next line after the return, never actually running. Here's the altered function:

var Chat = React.createClass({
  render: function () {
    return (
      <div>
        <p>{this.props.name}</p>
        <span> {this.props.message} </span>
      </div>
    );
  }
});

Also, for what it's worth, your App component is redundant. You could just do this:

React.render( <Chats {...messages} />, document.querySelector( '.container' ) );