Answer the question
In order to leave comments, you need to log in
How to fix "Invariant Violation: Objects are not valid as a React child" error?
I'm making a simple application using react and editor. Recently I started studying these technologies and got the following error:
Invariant Violation: Objects are not valid as a React child (found object with keys {name, author, descrip}). If you meant to render a collection of children, use an array instead or wrap the object using React.addons.createFragment(object).
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import getBook from '../actions/books';
import Radium from 'radium';
import {Link} from 'react-router';
function mapStateToProps(state) {
return {
books: state.book,
url: state.router.params.name,
};
}
function mapDispatchToProps(dispatch) {
return {
getBooks: () => dispatch(getBook()),
};
}
@Radium
@connect(mapStateToProps, mapDispatchToProps)
export default class bookPage extends Component {
static propTypes = {
url: PropTypes.string.isRequired,
books: PropTypes.array.isRequired,
};
render() {
const {books, url} = this.props;
return (
<ul>
{books.filter((book) => {
switch (book.name) {
case url:
return (<li >
<p>{book.name}</p>
<p><Link to={`/${book.author}`}>{book.author}</Link></p>
<p>{book.descrip}</p>
</li>);
default:
return 0;
}
})}
</ul>
);
}
}
Answer the question
In order to leave comments, you need to log in
What are you trying to do in the render method? The error says that you are rendering an object(s) instead of a react element.
You need to filter the books first and then render them as list items:
render() {
const {books, url} = this.props;
return (
<ul>
{books.filter(book => book.name === url).map((book, key) => (
<li key={key}>
<p>{book.name}</p>
<p><Link to={`/${book.author}`}>{book.author}</Link></p>
<p>{book.descrip}</p>
</li>
))}
</ul>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question