I am new to React JS, I was testing out some functions in fiddler. I am not sure why I get an error pointing to the map function. I am not able to render the array i defined.
Relevant snippet:
{this.props.data.productSpecs.map(function(productSpec){
<b>Category Name:</b> {productSpec};
})}
Full code:
var productCategory = {
productName: 'SamamgaTV1',
productCategory: 'Television',
productSpecs: ['32inch','black','hd']
};
var ProductComponent = React.createClass({
render: function() {
return( <div>
<h2>Product</h2>
<b>Product Name:</b> {this.props.data.productName}
<h2>Category</h2>
<b>Category Name:</b> {this.props.data.productCategory}
<h2>Specs</h2>
{this.props.data.productSpecs.map(function(productSpec){
<b>Category Name:</b> {productSpec};
})}
</div>);
}
});
ReactDOM.render(
<ProductComponent data={productCategory} />,
document.getElementById('container')
);
TypeError: map() is not a function in React # The "TypeError: map is not a function" occurs when we call the map() method on a value that is not an array. To solve the error, console. log the value you're calling the map() method on and make sure to only call map on valid arrays.
The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function.
To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.
First you missed to return
, then you must return ONE element.
Here you return a <p>
and a TextNode
Moreover you need to provide a unique key.
Try with this :
{this.props.data.productSpecs.map(function(productSpec, i){
return <span key={i}><b>Category Name:</b> {productSpec}</span>;
})}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With