Rolando
Rolando

Reputation: 62704

How to render array of objects in reactjs 1.0 with jsx?

I have the following:

var repos = [{"keya":"vala","keyb":"valb"},{"keya":"vala","keyb":"valb"},{"keya":"vala","keyb":"valb"}]

In my react component code:

var React = require('react');

var Repos = React.createClass({
    propTypes: {
        username: React.PropTypes.string.isRequired,
        repos: React.PropTypes.array.isRequired
    },
    render: function() {
        return (
            <div> REPOS<br />
                Username: {this.props.username} <br />
                Repos: {this.props.repos}           
            </div>
        )
    }
});

module.exports = Repos;

I see that: {this.props.repos} returns the above, but I am getting an error:

Uncaught Error: Invariant Violation: Objects are not valid as a React child... check the render method.

How do I get around this? Is there a way to just output everything without iterating/looping through each one? I know I can do so in AngularJS, but I don't get why react is giving me a hard time.

I am using the newest version of react; I don't think this was a problem with 0.13.

Upvotes: 1

Views: 1373

Answers (2)

Jonny Buchanan
Jonny Buchanan

Reputation: 62813

Stringify it:

{JSON.stringify(this.props.repos)}  

Upvotes: 1

nbermudezs
nbermudezs

Reputation: 2844

That depends on how you want to display the values in your HTML.

You could do something like

render: function() {
    return (
        <div> REPOS<br />
            Username: {this.props.username} <br />
            Repos:
            {this.props.repos.map(function(repo){
              return <div><span>{repo.keya}</span></div>;
            }}           
        </div>
    )
}

In general, you want to iterate over the array of values and return a HTML representation of it. That is why you are getting the error you mentioned, React doesn't provide a default HTML representation of an object so there is no way it will know how to display your array.

If you just want to display it as a text then the stringify method on the other answer is the way to go. But if you are expecting a pretty formatted output you will have to iterate over the array.

Upvotes: 0

Related Questions