Reputation: 4461
CODE:
var React = require('react');
var Ingredient = require('./Ingredient.jsx')
var Recipe = React.createClass({
getInitialState: function() {
return {
showIngredients: false
};
},
handleClick: function() {
this.setState({
showIngredients: !this.state.showIngredients
});
},
render: function() {
var i = 0;
var ingredientsList = this.props.ingredients.map(function(item) {
i++;
return <Ingredient key={i} name={item}/>;
});
return (
<table>
<tbody>
<tr className="recipeName" onClick={this.handleClick}>
<td>{this.props.name}</td>
</tr>
{this.state.showIngredients ? {ingredientsList} : null }
</tbody>
</table>
);
}
});
module.exports = Recipe;
This generates the following error:
main.js:18463 Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {ingredientsList}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of
Recipe
.
Upvotes: 0
Views: 1705
Reputation: 104369
Remove the {}
, that is not required here, Write it like this:
{this.state.showIngredients ? ingredientsList : null }
Or use a div
or tr
or any other html element
and render
the ingredientsList
inside that, like this:
{this.state.showIngredients ? <tr> {ingredientsList} </tr> : null }
Reason: {}
are required to put js
code inside html
elements, when you are using ternary operator
you are already inside js
no need of using {}
.
Check the example:
class App extends React.Component {
render() {
let a = [1,2,4].map(el=> <div key ={el}>{el}</div>)
return (
<div>
{1 == 1 ? a : null}
{1 == 1 ? <div> {a} </div> : null}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container' />
Upvotes: 1
Reputation:
The problem is that you're trying to render a plain JS object as a React element. You can render a plain JS array if its entries are React elements, which is what your ingredientsList
looks like. If you remove the brackets from around this array, I think this should work.
(i.e. change {ingredientsList}
to ingredientsList
)
Upvotes: 0